JonnyT
JonnyT

Reputation: 93

Axios fails CORS but fetch works fine

I've looked through all the other questions regarding CORS errors with no luck. I'm making a simple POST request in a NuxtJS client application. If I use axios, I get CORS errors, but if I use fetch, it works just fine. I would like to use axios, but I can't sort this out. The server has the correct "Access-Control-Allow-Origin" headers set (neither option below works when that header is removed). Anyone know why this would work for fetch but not axios?

FAILS

await this.$axios({
      url,
      method: 'POST',
      data
    })

WORKS

await fetch(url, {
      method: 'POST',
      body: JSON.stringify(data)
    })

Error message: Access to XMLHttpRequest at {URL} from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In the network tab of Chrome, the request headers show as follows:

Axios request headers

fetch request headers

Upvotes: 9

Views: 11706

Answers (2)

Quentin
Quentin

Reputation: 943510

When you send data in the body of an HTTP request, the request's Content-Type header specifies what type of data you are sending.

Since you are sending JSON the header should be Content-Type: application/json.

Since you are passing an object to axios, it encodes it as JSON and sets the proper Content-Type header automatically.

fetch doesn't do this automatically, you have to encode the data and set the Content-Type yourself. You've only done the first of these, so fetch is defaulting to claiming that you are sending plain text instead of JSON.

Your fetch code is in error.


For historical reasons, there are no special CORS requirements when you POST data using a format that you could send with a regular HTML form. text/plain is such a format.

Since application/json is not, the browser asks permission from the server using a CORS preflight request.

The server is not granting that permission.

It needs to respond with something like:

HTTP/1.1 204 No Content
Connection: keep-alive
Access-Control-Allow-Origin: https://foo.bar.org
Access-Control-Allow-Methods: POST, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400

Upvotes: 10

Michael
Michael

Reputation: 1076

Try adding withCredentials:

axios({
    method: "POST",
    url: "http://....",
    data: {},
    withCredentials: true
})

Upvotes: -3

Related Questions