Warm tip: This article is reproduced from serverfault.com, please click

Passing headers with axios POST request

发布于 2017-06-18 17:45:29

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

Any help is greatly appreciated.

Questioner
Jagrati
Viewed
0
31.1k 2019-07-30 15:20:54

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