312

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})
})
Jagrati
  • 11,474
  • 9
  • 35
  • 56

10 Answers10

551

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
    })
  })
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • @KishoreJethava, 500 is internal server error, can you check on server side if headers are coming or is there some other bug – Shubham Khatri Sep 25 '17 at 10:31
  • @KishoreJethava, can you just log the headers in your server and see if you are getting the correct values – Shubham Khatri Sep 25 '17 at 10:44
  • Dont you need to post any data? Also make sure this.state.token contains a value – Shubham Khatri Sep 25 '17 at 10:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155236/discussion-between-kishore-jethava-and-shubham-khatri). – Kishore Jethava Sep 25 '17 at 10:52
  • @ShubhamKhatri, may I ask you to have a look at an `axios` related question here : https://stackoverflow.com/questions/59470085/vue-js-validation-fails-for-file-upload-in-axios-when-multipart-form-data-used ? – Istiaque Ahmed Dec 24 '19 at 14:25
  • What are these dispatch methods used for? – Dipan Mandal Aug 06 '20 at 08:17
  • @DipanMandal dispatch is used to update the redux store from within actions. A redux-thunk middleware is involved in this syntax too – Shubham Khatri Aug 06 '20 at 10:30
  • if i try this then my header is going as [object, object]. plz help! – amitava mozumder Mar 10 '21 at 14:40
  • This works for me, but I needed to base 64 encode my auth token with... `const encodedAPIKey = Buffer.from(APIKey).toString('base64');` and I also prepended `Basic` – PGallagher May 20 '21 at 09:29
  • My issue was that I had Headers instead of headers. It is case sensitive, keep in mind. – Peter Palmer Nov 15 '21 at 13:01
  • Thanks for the example, took me a stupid amount of time to figure this out. – Alex Bishka Dec 21 '21 at 17:19
  • the answer which worked for 467 members is not helping for me.don't know what is the issue.i am also following the above answer in my application.but i am getting auth error.usually the auth error will come for me when header is not available. – Vishali Jun 14 '22 at 15:32
73

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

var postData = {
  email: "test@test.com",
  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);
})
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61
  • facing this issue for get request. The response is coming in xml format. This doesn't solve the problem. – Eswar Feb 05 '19 at 13:37
  • 1
    for that you need to add `headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", "Accept": "application/json" }` Please note this only works if your api supports json response – Akhil Oct 08 '20 at 12:02
  • Why is this getting upvoted so much? `Access-Control-Allow-Origin` is a **response** header and has no effect on request headers sent in JavaScript... – Heretic Monkey Aug 23 '23 at 14:23
36

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}`
  }
})
Lalit Mohan
  • 2,685
  • 2
  • 16
  • 16
8

const data = {
  email: "me@me.com",
  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

Fahd Jamy
  • 365
  • 6
  • 7
6

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;
});
Israel kusayev
  • 833
  • 8
  • 20
4

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})
    })
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
4

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);
    });
};
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81
1

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})
})
0

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");
    });
};
Dach0
  • 309
  • 4
  • 11
0

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);
  });
toraman
  • 598
  • 4
  • 14