如何在 Node/Express 中为凭据和预检启用 CORS
Posted
技术标签:
【中文标题】如何在 Node/Express 中为凭据和预检启用 CORS【英文标题】:How to Enable CORS for Credentials and Preflight in Node/Express 【发布时间】:2020-09-15 11:36:31 【问题描述】:我知道,这里有十亿个 CORS 问题。我经历了几十个。我仍然不确定问题出在哪里,我认为我对 CORS 的理解还不错,但显然我在这里遗漏了一些东西。
我正在尝试让我的 (Node/Express) API 在真实 URL 上运行(即已部署,而不是使用 origin: "*"
),并告诉浏览器实际满足来自我的 GUI 的 URL 的请求。
对于某些路由,我需要认证,所以我需要在里面添加credentials
。
这是一个非常标准的用例,但自从我上次这样做以来,API 可能发生了一些变化,或者我只是忘记了,但无论如何我似乎无法让它工作,我不确定我在做什么不见了。
似乎有几种方法可以为我的 Express 应用中的所有请求启用 CORS。我目前正在使用 cors
中间件及其选项对象。
具体来说,这是我正在使用的代码。
const app: express.Application = express();
const corsOptions =
credentials: true,
origin: 'https://my-gui.example.com',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: true,
app.use(cors(corsOptions));
我做错了什么?当我从浏览器发出fetch
请求时,我收到以下错误。
Access to fetch at 'https://my-api.example.com/graphql' from origin 'https://my-gui.example.com'
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. If an
opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource
with CORS disabled.
如果我在app.use
调用之前添加app.options('*', cors(corsOptions));
(为什么我在method
列表中指定OPTIONS
时需要这个,我不知道),我得到一个不同的错误(这导致我相信我出于某种原因确实需要这个)。
Access to fetch at 'https://my-api.example.com/graphql' from origin 'https://my-gui.example.com'
has been blocked by CORS policy: Response to preflight request doesn't pass access control
check: It does not have HTTP ok status.
【问题讨论】:
【参考方案1】:我认为您正在尝试访问此网站 https://my-api.example.com/graphql
,但共享的片段看起来您仅授予了对 https://my-gui.example.com
的访问权限,这与上述不同。
所以我的回答是请像下面这样更改您的 sn-p,
const corsOptions =
credentials: true,
origin: "*",
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: true,
(或)尝试
const corsOptions =
credentials: true,
origin: ['https://my-gui.example.com','https://my-api.example.com/graphql'],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: true,
【讨论】:
1.我正在尝试从https://my-gui.example.com
访问https://my-api.example.com/graphql
。 2. CORS 源忽略路径(和查询参数),所以/graphql
不是必需的。 3. 同样,我不想允许"*"
,我希望这是安全的,并将请求发出的实际域列入白名单。 4. 可以肯定的是,我测试了建议的代码,但它不起作用(我仍然收到Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
)。以上是关于如何在 Node/Express 中为凭据和预检启用 CORS的主要内容,如果未能解决你的问题,请参考以下文章
如何在 xamarin 中为 iOS 12 添加凭据提供程序应用程序扩展
Access-Control-Allow-Headers - Node / Express / KeystoneJs不允许使用标头字段
如何从 C# WebApi 禁用对 MarkLogic 服务器的预检请求