axios: Setting header: 'Content-Type': 'application/json' is not working
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?
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 71
- Comments: 30 (1 by maintainers)
Yep, I can confirm. If there is no
datapassed it removes the Content-Type… I just addeddata: {}to myGETrequest, and it works fine. It’s really weird to pass data on get requests but I don’t mind 👍If a user of this package wants to set a
Content-Typeheader 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 theContent-Typeheader from being set. This choice should be up to the user unless there is a good reason to prevent it.Just for other people Googling, this is how I had to format my axios.post request
This stills an issue. You need to specify the data:null or data:{} to get it to work 😃
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
Same issue successfully fixed with
data: {}. I hope, it will work ‘from the box’ soon.Please reopen this ticket. This is still an issue for me too.
Currently performing a
PUTwithfileandContent-Typeheader.Content-Typeheader is lost, unless I adddata:{}to theconfig. But then thefileget lost if I do that.@SirSerje While it is probably a good idea to set a default
Acceptheader, I just want to point out that theAcceptheader isn’t the same asContent-Type. TheContent-Typetells your server the format you, as the client, are sending the server.Accepttells your server the format in which you, as the client, want response data.This bears repeating: if you’re here and you want
Content-Typeto 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 usingAcceptinstead. See this SO question.@teleyinex
Content-Typedescribes what format the request data is in. If there is no request data, there is no need to specify theContent-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 ifdatais null. What do you think?Yeah, agreed about that, it’s definitely something worth documenting.
One example in the README will do the trick 😄
@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:This is still an issue. I have to do this if I want the content type to be application/json