我有一个 Node.js(
v20.10.0
) 后端服务器,使用 Fastify(v4.26.2
) 作为框架。
我有 index.js 作为入口点。
import Fastify, { FastifyInstance, FastifyServerOptions } from 'fastify';
import cors from '@fastify/cors';
// Assuming other settings and configurations already written.
fastify.register(cors, {
origin: "https://dev.example.com",
credentials: true,
});
我有一个
GET
API 调用用于列出用户 https://api-dev.example.com/api/v1/users
,它工作正常。
但是问题出在
POST
API 上,我可以在其中创建用户 https://api-dev.example.com/api/v1/create-user
。
使用任何
POST
API 时,我得到 CORS Error
从源“https://dev.example.com”访问“https://api-dev.example.com/api/v1/users”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应不会” t 通过访问控制检查:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“*”。请求的凭证模式
尝试了多种方法,仍然出现同样的错误。
fastify.register(cors, {
origin: "*",
credentials: true,
});
通过错误,我可以理解
OPTION
请求正在获取
在响应标题中Access-Control-Allow-Origin: *
这就是我收到此错误的原因。
但在所有
GET
API 响应标头中 Access-Control-Allow-Origin: https://dev.example.com
我不知道为什么在
OPTION
请求POST
之前的Access-Control-Allow-Origin
请求是*
如果您的 GET 请求工作正常,但您遇到 POST 或 PATCH 请求问题,则根据您的错误
Access to XMLHttpRequest at 'https://api-dev.example.com/api/v1/users' from origin 'https://dev.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests
此错误表示浏览器正在向服务器发送 OPTIONS 请求,其中“Access-Control-Allow-Origin”标头设置为通配符“*”,而您的服务器仅接受特定来源。
这背后的原因是每个 POST 和 PATCH 请求都会发起一个预检请求。 与简单请求不同,对于“预检”请求,浏览器首先使用 OPTIONS 方法向服务器发送 HTTP 请求,以确定服务器是否选择从服务器接收跨源 POST 或 PATCH 请求
要解决这个问题,你可以尝试 在你的 cors 选项中添加 optionsSuccessStatus: 200 ,如下所示
fastify.register(cors, {
origin: "https://dev.example.com",
credentials: true,
optionsSuccessStatus: 200,
});
使用 optionsSuccessStatus: 200,服务器会针对成功的预检请求响应 200 OK 状态代码。这向浏览器表明服务器已配置为接受跨域请求。
现在服务器已确认成功的预检请求,您的 POST 和 PATCH 方法应该可以正常运行,而不会遇到与 CORS 相关的问题。