[英]Fetch API CORS error: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response
I'm trying to get data from an API of mine and I'm getting this error message in Chrome:我正在尝试从我的 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.
Since it's CORS, Chrome is doing a OPTIONS preflight request, which gets a 204 response with the following headers back:由于它是 CORS,Chrome 正在执行一个 OPTIONS 预检请求,它会收到一个 204 响应,并返回以下标头:
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:然后它使用以下标头发出所需的 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
And finally, here is the base code for the request (JS Fetch API):最后,这是请求的基本代码(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?对可能发生的事情有任何想法吗?
You need to set access-control-allow-headers
in the preflight response, eg:您需要在预检响应中设置
access-control-allow-headers
,例如:
access-control-allow-headers: *
You can read more about Access-Control-Request-Headers and Access-Control-Allow-Headers您可以阅读更多关于Access-Control-Request-Headers和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, eg:您可能还需要在预检响应中设置
access-control-allow-methods
,例如:
access-control-allow-methods: GET, POST, PUT, PATCH, OPTIONS, DELETE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.