Axios: Adding headers to axios.post method

Created on 24 Apr 2017  ·  17Comments  ·  Source: axios/axios

Hi,

I tried to make a post request to cross-domain IP and my code looks like;

  var authOptions = {
    method: 'POST',
    url: 'http://10.254.147.184:7777/auth/oauth/token',
    data: qs.stringify(data),
    headers: {
        'Authorization': 'Basic Y2xpZW50OnNlY3JldA==',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    json: true
  };
  return dispatch => {
    return axios(authOptions)
    .then(function(response){
      console.log(response.data);
      console.log(response.status);
    })
    .catch(function(error){
      console.log(error);
    });

But whenever I add 'headers' to it, my request automatically turns into 'OPTIONS' from 'POST' method and I don't know why. Is there a bug about it or anything I couldn't find?

Most helpful comment

Edit: I had to add Authorization to allowed headers in my CORS filter


@jffernandez

I'm having the same issue. When I leave out the Auth header I'm getting an Options request which returns POST, OPTIONS and then the POST which returns a 403 because it's missing the Authorization header (expected).

When I add the header I just get the option request and it never makes the POST.

post("http://localhost:8080/foo", foo)

vs

post("http://localhost:8080/foo", foo, {
    headers: { Authorization: "Bearer " + token }
})

All 17 comments

This is not a bug, it's working as expected.
You are generating a preflighted request (not a simple one) as stated in the docs https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS because you are adding a header and a content-type that forces this.
So, in this mode, an OPTIONS request is issued before your main request, you must ensure the server can manage the OPTIONS request for it to work.

Edit: I had to add Authorization to allowed headers in my CORS filter


@jffernandez

I'm having the same issue. When I leave out the Auth header I'm getting an Options request which returns POST, OPTIONS and then the POST which returns a 403 because it's missing the Authorization header (expected).

When I add the header I just get the option request and it never makes the POST.

post("http://localhost:8080/foo", foo)

vs

post("http://localhost:8080/foo", foo, {
    headers: { Authorization: "Bearer " + token }
})

It's a CORS issue, not in axios. Please take a look at the link @jffernandez provided or look for similar issues here.

Yes it's about CORS. But if you are like me, then you likely forgot to add Content-Type authorized in your api server.

AllowedHeaders : Content-Type and X-Requested-With
And authorization in your case.

And of course, don't forget to allow method OPTIONS also.

axios({ method: 'POST', url: 'you http api here', headers: {autorizacion: localStorage.token}, data: { user: 'name' } })

Or if you want to get over this CORS error you can install corsproxy package in your node. This will help you with cross origin errors. You can refer to the link below:

https://github.com/gr2m/CORS-Proxy

````
SignIn = () => {
console.log('login clicked')
let data = JSON.stringify({
password: this.state.password,
username: this.state.email
})

axios.post('url', data, {
    headers: {
        'Content-Type': 'application/json',
    }
}
)

}
```

Solve it by adding this header

   axios.post('http://localhost/M-Experience/resources/GETrends.php',
      {
        firstName: this.name
      },
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });

This is how I had to format my POST request

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

to solve cors error simply run this command npm i --save cors and then in your app.js import like this

var cors = require('cors');
then call like this in same file in my case my root file is app.js
app.use(cors());

it will solve your cors issue

@mirzaumersaleem I'm not using the cors but I'm trying to post to my backend using axios and I'm getting a 400 Bad request

fetch can do with cors(the backend is not have a problem), but with axios, sometime failed.

to solve cors error simply run this command npm i --save cors and then in your app.js import like this

var cors = require('cors');
then call like this in same file in my case my root file is app.js
app.use(cors());

it will solve your cors issue

In my travels, CORS needs to be done on the server ( .net /java/node/php etc..)

Edit: I had to add Authorization to allowed headers in my CORS filter

@jffernandez

I'm having the same issue. When I leave out the Auth header I'm getting an Options request which returns POST, OPTIONS and then the POST which returns a 403 because it's missing the Authorization header (expected).

When I add the header I just get the option request and it never makes the POST.

post("http://localhost:8080/foo", foo)

vs

post("http://localhost:8080/foo", foo, {
    headers: { Authorization: "Bearer " + token }
})

the quick answer is that first argument after url and second is often misplaced, i.e. axios(url, data, config), so if you omit config part or switched data and config you probably get unexpected results, in general, working with localhost should be without any issues at all.

In general, it it not very readable

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

I expected that all api are consistent, and have
1) url as first parameter,
2) config as second parameter (optional),
3) data (optional)

cause that is what users expects, despite that, axios made a huge problem from that little tiny api decision, so that almost everyone trapped there at least once in a lifetime.

Wrok for me :

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

Facing the same issue here with jquery the request are successful but when I send the req with axios getting cors issue.
My request--

      .post('https://test.pi.com/j_spring_security_check', {

        withCredentials: true,
        crossorigin: true,
        headers: {
          common:{
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'WithCredentials': true,
            'Access-Control-Allow-Origin': '*'
        }
      },
        data: JSON.stringify({
          j_username: email,
          j_password: password
        }),

        // proxy: {
        //   '/j_spring_security_check/*': 'https://devtest.pvai.com/j_spring_security_check',
        // }
      })

these are the response headers from the server and my locahost origin is allowed the headers I am sending are allowed and methods also.

access-control-allow-credentials: true
access-control-allow-headers: Authorization, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept
access-control-allow-methods: POST, GET, OPTIONS
access-control-allow-origin: http://localhost:5000
access-control-expose-headers: Authorization
cache-control: no-cache, no-store, max-age=0, must-revalidate
content-length: 0
date: Wed, 11 Dec 2019 04:53:25 GMT
expires: 0
location: /authFailure
pragma: no-cache
status: 302
strict-transport-security: max-age=31536000 ; includeSubDomains
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block

This is how I had to format my POST request

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

Thanks , saved my day ! Worked for me

Was this page helpful?
0 / 5 - 0 ratings