Fetch API CORS error: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response

Fetch API CORS error: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response

我正在尝试从我的 API 中获取数据,但我在 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.

因为它是 CORS,Chrome 正在执行一个 OPTIONS 预检请求,它得到一个 204 响应,headers 返回:

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

然后它使用以下 headers 发出所需的 POST 请求:

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

最后,这里是请求的基本代码(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

对可能发生的事情有什么想法吗?

您需要在预检响应中设置access-control-allow-headers,例如:

access-control-allow-headers: *

您可以阅读有关 Access-Control-Request-Headers and Access-Control-Allow-Headers

的更多信息

headers

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

属于请求,不属于响应。您可能还需要在预检响应中设置 access-control-allow-methods,例如:

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