Home > Software engineering >  Fetch API CORS error: Request header field authorization is not allowed by Access-Control-Allow-Head
Fetch API CORS error: Request header field authorization is not allowed by Access-Control-Allow-Head

Time:05-11

I'm trying to get data from an API of mine and I'm getting this error message in Chrome:

Access to fetch at 'https://myapi.amazonaws.com/accounts' from origin 'http://localhost:3000' 
has been blocked by CORS policy: Request header field authorization is not allowed by 
Access-Control-Allow-Headers in preflight response.

Since it's CORS, Chrome is doing a OPTIONS preflight request, which gets a 204 response with the following headers back:

access-control-allow-credentials: true
access-control-allow-origin: *
access-control-max-age: 3600
access-control-request-headers: *
access-control-request-method: GET, POST, PUT, PATCH, OPTIONS, DELETE
apigw-requestid: R64AgjukPHcEJWQ=
charset: utf-8
date: Tue, 10 May 2022 17:27:05 GMT

Then it makes the desired POST request with the following headers:

accept: application/json
authorization: Bearer some.very.long.string
Referer: http://localhost:3000/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36

And finally, here is the base code for the request (JS Fetch API):

const result = await fetch(`${process.env.MY_API_URL}/accounts`, {
  method: 'POST',
  mode: 'cors',
  headers: new Headers(
    Accept: 'application/json',
    'Accept-Encoding': 'gzip, deflate, br',
    Connection: 'keep-alive',
    Authorization: `Bearer ${accessToken}`,
  ),
  body: JSON.stringify({
    accountId,
    name,
  }),
})

if (!result.ok || result.status !== 200)
  throw new Error("Couldn't get data")

const jsonResponse = await result.json()

return jsonResponse

Any thoughts on what might be going on?

CodePudding user response:

You need to set access-control-allow-headers in the preflight response, e.g.:

access-control-allow-headers: *

You can read more about Access-Control-Request-Headers and Access-Control-Allow-Headers

The headers

access-control-request-headers: *
access-control-request-method: GET, POST, PUT, PATCH, OPTIONS, DELETE

belong into the request, not into the response. You probably also need to set access-control-allow-methods in the preflight response, e.g.:

access-control-allow-methods: GET, POST, PUT, PATCH, OPTIONS, DELETE
  • Related