Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting header: 'Content-Type': 'application/json' is not working #86

Closed
alejandronanez opened this issue Jul 13, 2015 · 30 comments
Closed

Comments

@alejandronanez
Copy link

Hi. I'm passing a custom header like this

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

But it doesn't seem to work. Any ideas?

@mzabriskie
Copy link
Member

There was an issue with Content-Type having to be cased correctly (see #89). I just fixed it a few minutes ago. Maybe this was the same issue you were experiencing?

@alejandronanez
Copy link
Author

Well, I wasn't able to send the header 'Content-type' at all on my request. @mzabriskie let me give it a try and I'll let you know.

Thanks.

@mcmire
Copy link

mcmire commented Aug 18, 2015

This doesn't appear to be working for me, either. It looks like perhaps it's this line here? https://github.com/mzabriskie/axios/blob/master/lib/adapters/xhr.js#L77

@aprzywara
Copy link

Is your request body empty by any chance?
For me manually passing data: null to axios, in order to manually set an empty body, prevented IE from sending undefined as body.

@mcmire
Copy link

mcmire commented Aug 31, 2015

Yeah, the request body was empty.

On closer inspection, it appears that Axios is doing the right thing here. Content-Type only applies to the request body, so if it's missing then it shouldn't pass along that header.

@aprzywara
Copy link

Yes it is correct to remove the headers, you need to pass on an empty body though (IE does not do that, it passes "undefined" which triggers errors in some/most backends).

We are using Restler in a project to serve JSON and Restler was throwing 403 errors because the "undefined" string gets passed as Content-Type: text/plain which doesn't work.

@dinodsaurus
Copy link

dinodsaurus commented Sep 11, 2015

Yep, I can confirm. If there is no data passed it removes the Content-Type...
I just added data: {} to my GET request, and it works fine.
It's really weird to pass data on get requests but I don't mind 👍

@mcmire
Copy link

mcmire commented Sep 11, 2015

I'd vote for this issue to be closed, then. @alejandronanez what do you think?

@teleyinex
Copy link

This stills an issue. You need to specify the data:null or data:{} to get it to work :-)

@mcmire
Copy link

mcmire commented Jun 28, 2017

@teleyinex Content-Type describes what format the request data is in. If there is no request data, there is no need to specify the Content-Type. So you can correct me if I'm wrong but I believe the present behavior makes sense, aside from the fact that it should still not add the header if data is null. What do you think?

@teleyinex
Copy link

@mcmire then I agree completely. But, it might be good to add this to the docs, so others can easily find it.

@mcmire
Copy link

mcmire commented Jun 29, 2017

Yeah, agreed about that, it's definitely something worth documenting.

@teleyinex
Copy link

One example in the README will do the trick :D

@BenAhlander
Copy link

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

@mdrideout
Copy link

mdrideout commented Jan 27, 2018

Just for other people Googling, this is how I had to format my axios.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);
    })

@EJIqpEP
Copy link

EJIqpEP commented May 15, 2018

Is there a particular reason to remove content-type in this line if data is not provided?
https://github.com/axios/axios/blob/master/lib/adapters/xhr.js#L135
Why my get request can't have content-type: application/json?
This is super strange to write everywhere

await axios.get(url, {data: null})

@dinodsaurus
Copy link

@EJIqpEP check what @mcmire said.. so basically you need to handle this on your backend

@EJIqpEP
Copy link

EJIqpEP commented May 16, 2018

Thanks for clarifying @dinodsaurus.

@SirSerje
Copy link

const config = {
  headers: {
    accept: 'application/json',
  },
  data: {},
};

Same issue successfully fixed with data: {}. I hope, it will work 'from the box' soon.

@mcmire
Copy link

mcmire commented Jul 18, 2018

@SirSerje While it is probably a good idea to set a default Accept header, I just want to point out that the Accept header isn't the same as Content-Type. The Content-Type tells your server the format you, as the client, are sending the server. Accept tells your server the format in which you, as the client, want response data.

This bears repeating: if you're here and you want Content-Type to always be set because you're using it on the server side to figure out which format to send data back, then that's incorrect; you want to be using Accept instead. See this SO question.

@SirSerje
Copy link

@mcmire I've just needed to fix the hole quickly. Now I can go by more sophisticated way, thank you for clarification.

@adamrbennett
Copy link

If a user of this package wants to set a Content-Type header without a body, shouldn't they be able to do that? I don't see the argument for limiting the use here by either forcing a dummy payload or preventing the Content-Type header from being set. This choice should be up to the user unless there is a good reason to prevent it.

@DrCord
Copy link

DrCord commented Jun 11, 2019

This comes up for AWS API Gateway endpoints - you want to do a PUT request to an endpoint that expects content type of application/json and the request doesn't work unless you send an empty body, which is contrary to how a PUT request should be sent...

@madroneropaulo
Copy link

madroneropaulo commented Nov 1, 2019

This is still an issue. I have to do this if I want the content type to be application/json

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

@marcocali
Copy link

marcocali commented Nov 5, 2019

Please reopen this ticket. This is still an issue for me too.

Currently performing a PUT with file and Content-Type header.
Content-Type header is lost, unless I add data:{} to the config. But then the file get lost if I do that.

Screen Shot 2019-11-05 at 3 54 26 pm

Screen Shot 2019-11-05 at 3 52 31 pm

@ziaulrehman40
Copy link

Something weird, or just something related to rails, but when i append .json at the end of the url for my put request, it correctly goes as json request.

Was struggling for some time on this issue.

@maxflex
Copy link

maxflex commented Feb 7, 2020

Reopen the issue

@arefaslani
Copy link

@ziaulrehman40 @alejandronanez It seems you guys are using Rails and expect Rails to respond with JSON. The problem is that you're setting the wrong HTTP header to accept JSON as a response. The header you should set is Accept:

axios.get('my/url', {
    headers: {
        'Content-Type': 'application/json',
         Accept: 'application/json'
    }
})

@dariuszsikorski
Copy link

I found a workaround by simply setting empty data in the request, so Axios assumed the Content-Type is application/json;charset=utf-8, but even if it works I would prefer Axios to respect every type of header in GET request.

Hope this helps.

axios.get(some/url', {
  data: {},
})

@manhengest
Copy link

this example fixed for me the issue

  axios({
      method: 'get',
      url: '/url',
      headers: {'X-Requested-With': 'XMLHttpRequest'},
      params: {
        category_id: 3,
        page: this.page,
      },
    }).then(response => {

    }).catch(error => {
      console.log(error);
    });

@axios axios locked and limited conversation to collaborators May 21, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests