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 'Content-Type' header does not work. #2544

Closed
star-collector opened this issue Nov 12, 2019 · 3 comments
Closed

Setting 'Content-Type' header does not work. #2544

star-collector opened this issue Nov 12, 2019 · 3 comments

Comments

@star-collector
Copy link

star-collector commented Nov 12, 2019

It seems like setting Content-Type header is impossible without data property:

const api = Axios.create({
  baseURL: 'https://my-url',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
});

api.post('/post-something'); // The request doesn't contain 'Content-Type' header.
api.get('/get-something', {
  headers: { 'Content-Type': 'application/json' }
}); // Still no 'Content-Type' header.

api.post('/post-something', null); // Works. 'Content-Type' is present in the request.
api.get('/get-something', {
  data: {},
  headers: { 'Content-Type': 'application/json' }
}); // Works as well.
@Alanscut
Copy link
Collaborator

indeed, in browser environment, the Content-Type will be removed if data is undefined. Because there is no need to set the Content-Type when no data to transfer.

axios/lib/adapters/xhr.js

Lines 119 to 129 in 8414664

if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}

@star-collector
Copy link
Author

star-collector commented Nov 12, 2019

Because there is no need to set the Content-Type when no data to transfer.

Some backend systems still require it to be passed specifically, even if there are no data to transfer. Backend I have to work with returns an error when there is no Content-Type present.

Also, it seems like the same bug was already fixed once. #86

@Alanscut
Copy link
Collaborator

That fix(3c4dfe8) actually was about case of content-type #86 (comment) , mzabriskie mistakenly thought that #86 is the same kind of problem, so this issue still exists.
As you said, setting Content-Type header is impossible without data property currently.

@yasuf , should axios surpport this feature?

@axios axios locked and limited conversation to collaborators May 22, 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

2 participants