Passing headers with axios POST request

AxiosHttp Headers

Axios Problem Overview


I have written an Axios POST request as recommended from the npm package documentation like:

var data = {
    'key1': 'val1',
    'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)		
.then((response) => {
	dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
	dispatch({type: ERROR_FINDING_USER})
})

And it works, but now I have modified my backend API to accept headers.

> Content-Type: 'application/json' > > Authorization: 'JWT fefege...'

Now, this request works fine on Postman, but when writing an axios call, I follow this link and can't quite get it to work.

I am constantly getting 400 BAD Request error.

Here is my modified request:

axios.post(Helper.getUserAPI(), {
	headers: {
		'Content-Type': 'application/json',
		'Authorization': 'JWT fefege...'
	},
	data
})		
.then((response) => {
	dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
	dispatch({type: ERROR_FINDING_USER})
})

Axios Solutions


Solution 1 - Axios

When using Axios, in order to pass custom headers, supply an object containing the headers as the last argument

Modify your Axios request like:

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'JWT fefege...'
}

axios.post(Helper.getUserAPI(), data, {
    headers: headers
  })
  .then((response) => {
    dispatch({
      type: FOUND_USER,
      data: response.data[0]
    })
  })
  .catch((error) => {
    dispatch({
      type: ERROR_FINDING_USER
    })
  })

Solution 2 - Axios

Here is a full example of an axios.post request with custom headers

var postData = {
  email: "[email protected]",
  password: "password"
};

let axiosConfig = {
  headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "Access-Control-Allow-Origin": "*",
  }
};

axios.post('http://<host>:<port>/<path>', postData, axiosConfig)
.then((res) => {
  console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
  console.log("AXIOS ERROR: ", err);
})

Solution 3 - Axios

To set headers in an Axios POST request, pass the third object to the axios.post() call.

const token = '..your token..'

axios.post(url, {
  //...data
}, {
  headers: {
    'Authorization': `Basic ${token}` 
  }
})

To set headers in an Axios GET request, pass a second object to the axios.get() call.

const token = '..your token..' 

axios.get(url, {
  headers: {
    'Authorization': `Basic ${token}`
  }
})

Solution 4 - Axios

const data = {
  email: "[email protected]",
  username: "me"
};

const options = {
  headers: {
      'Content-Type': 'application/json',
  }
};

axios.post('http://path', data, options)
 .then((res) => {
   console.log("RESPONSE ==== : ", res);
 })
 .catch((err) => {
   console.log("ERROR: ====", err);
 })

All status codes above 400 will be caught in the Axios catch block.

Also, headers are optional for the post method in Axios

Solution 5 - Axios

You can also use interceptors to pass the headers

It can save you a lot of code

axios.interceptors.request.use(config => {
  if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

  const accessToken = AuthService.getAccessToken();
  if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;

  return config;
});

Solution 6 - Axios

Shubham's answer didn't work for me.

When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization.

The below example is working fine.

var headers = {
    'Content-Type': 'application/json',
    'Authorization': 'JWT fefege...' 
}

axios.post(Helper.getUserAPI(), data, {"headers" : headers})
    .then((response) => {
        dispatch({type: FOUND_USER, data: response.data[0]})
    })
    .catch((error) => {
        dispatch({type: ERROR_FINDING_USER})
    })

Solution 7 - Axios

We can pass headers as arguments,

onClickHandler = () => {
  const data = new FormData();
  for (var x = 0; x < this.state.selectedFile.length; x++) {
    data.append("file", this.state.selectedFile[x]);
  }

  const options = {
    headers: {
      "Content-Type": "application/json",
    },
  };

  axios
    .post("http://localhost:8000/upload", data, options, {
      onUploadProgress: (ProgressEvent) => {
        this.setState({
          loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100,
        });
      },
    })
    .then((res) => {
      // then print response status
      console.log("upload success");
    })
    .catch((err) => {
      // then print response status
      console.log("upload fail with error: ", err);
    });
};

Solution 8 - Axios

axios.post can accept 3 arguments that the last argument can accept a config object that you can set header.

Sample code with your question:

var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data, {
		headers: {Authorization: token && `Bearer ${ token }`}
})       
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

Solution 9 - Axios

If you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.

storePropertyMaxSpeed(){
  axios
    .post(
      "api/property",
      {
        property_name: "max_speed",
        property_amount: this.newPropertyMaxSpeed,
      },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + this.$gate.token(),
        },
      }
    )
    .then(() => {
      //this below peace of code isn't important
      Event.$emit("dbPropertyChanged");

      $("#addPropertyMaxSpeedModal").modal("hide");

      Swal.fire({
        position: "center",
        type: "success",
        title: "Nova brzina unešena u bazu",
        showConfirmButton: false,
        timer: 1500,
      });
    })
    .catch(() => {
      Swal.fire("Neuspješno!", "Nešto je pošlo do đavola", "warning");
    });
};

Solution 10 - Axios

Interceptors

I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJagratiView Question on Stackoverflow
Solution 1 - AxiosShubham KhatriView Answer on Stackoverflow
Solution 2 - AxiosMatthew RideoutView Answer on Stackoverflow
Solution 3 - AxiosLalit MohanView Answer on Stackoverflow
Solution 4 - AxiosFahd JamyView Answer on Stackoverflow
Solution 5 - AxiosIsrael kusayevView Answer on Stackoverflow
Solution 6 - AxiosHemadri DasariView Answer on Stackoverflow
Solution 7 - AxiosCodemakerView Answer on Stackoverflow
Solution 8 - Axiosmahdi momeniView Answer on Stackoverflow
Solution 9 - AxiosDach0View Answer on Stackoverflow
Solution 10 - AxiostoramanView Answer on Stackoverflow