Patrick Kenny
Patrick Kenny

Reputation: 6397

How to set `Content-Type` in headers in Axios?

I'm having trouble setting the Content-Type header in axios. Here's my code:

axios({
    url: fetchUrl,
    data: JSON.stringify(fetchOptions.body),
    method: 'POST',
    headers: {
      'Content-Type': 'application/vnd.api+json',
      Accept: 'application/vnd.api+json',
    },
  })

And here's the request headers:

axios request headers

Accept is set correctly but Content-Type is not. (Confirmed by removing Accept in my code, in which case the request header reverts to json isntead of vnd.api+json.)

When I change Content-Type to ContentType, then I see ContentType in the Response headers, so the problem is specifically with Content-Type.

Upvotes: 2

Views: 7884

Answers (1)

Patrick Kenny
Patrick Kenny

Reputation: 6397

It turns out that this error was the result of having an empty data; the property was called data, but I mistakenly called body:

axios({
    url: fetchUrl,
    data: JSON.stringify(fetchOptions.data),
    method: 'POST',
    headers: {
      'Content-Type': 'application/vnd.api+json',
      Accept: 'application/vnd.api+json',
    },
  })

Upvotes: 4

Related Questions