Passing headers with axios POST request

533,135

Solution 1

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

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

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

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

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;
});
Share:
533,135

Related videos on Youtube

Jagrati
Author by

Jagrati

By Day : Work and Code on different applications such as ReactJS, Golang, HTML....... For Fun : Photo Editing, Singing Moto : Fake it Till You make it

Updated on August 12, 2021

Comments

  • Jagrati
    Jagrati almost 3 years

    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})
    })
    
  • Shubham Khatri
    Shubham Khatri almost 7 years
    @KishoreJethava, 500 is internal server error, can you check on server side if headers are coming or is there some other bug
  • Shubham Khatri
    Shubham Khatri almost 7 years
    @KishoreJethava, can you just log the headers in your server and see if you are getting the correct values
  • Shubham Khatri
    Shubham Khatri almost 7 years
    Dont you need to post any data? Also make sure this.state.token contains a value
  • Kishore Jethava
    Kishore Jethava almost 7 years
  • Eswar
    Eswar over 5 years
    facing this issue for get request. The response is coming in xml format. This doesn't solve the problem.
  • Istiaque Ahmed
    Istiaque Ahmed over 4 years
    @ShubhamKhatri, may I ask you to have a look at an axios related question here : stackoverflow.com/questions/59470085/… ?
  • Constantine
    Constantine about 4 years
    I would suggest to use config.method.toUpperCase()
  • Constantine
    Constantine about 4 years
    Unfortunately, mine was lower
  • Dipan Mandal
    Dipan Mandal almost 4 years
    What are these dispatch methods used for?
  • Shubham Khatri
    Shubham Khatri almost 4 years
    @DipanMandal dispatch is used to update the redux store from within actions. A redux-thunk middleware is involved in this syntax too
  • Akhil
    Akhil over 3 years
    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
  • amitava mozumder
    amitava mozumder over 3 years
    if i try this then my header is going as [object, object]. plz help!
  • PGallagher
    PGallagher about 3 years
    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
  • Peter Palmer
    Peter Palmer over 2 years
    My issue was that I had Headers instead of headers. It is case sensitive, keep in mind.
  • Alex Bishka
    Alex Bishka over 2 years
    Thanks for the example, took me a stupid amount of time to figure this out.
  • Vishali
    Vishali about 2 years
    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.