本文介绍了在 Node.js 中为多个域启用 Access-Control-Allow-Origin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 node.js 中允许 CORS,但问题是我无法将 * 设置为 Access-Control-Allow-Origin 如果 >Access-Control-Allow-Credentials 已设置.

I'm trying to allow CORS in node.js but the problem is that I can't set * to Access-Control-Allow-Origin if Access-Control-Allow-Credentials is set.

规范还说我不能为 Access-Control-Allow-Origin 做一个数组或逗号分隔值,建议的方法是做类似于这个 Access-Control-Allow-Origin 多源域?

Also the specification said I can't do an array or comma separated value for Access-Control-Allow-Origin and the suggested method would be to do something similar to this Access-Control-Allow-Origin Multiple Origin Domains?

但我似乎不能在 node.js 中这样做

But I can't seem to do this way in node.js

["http://example.com:9001", "http://example.com:5001"].map(domain => {
  res.setHeader("Access-Control-Allow-Origin", domain);
});
res.header("Access-Control-Allow-Credentials", true);

这里的问题是它被数组中的最后一个值覆盖,因此标题将设置为 res.setHeader("Access-Control-Allow-Origin", "http://example.com:5001");

The problem here is that it's bein override by the last value in the array, so the header will be set to res.setHeader("Access-Control-Allow-Origin", "http://example.com:5001");

来自客户端浏览器的错误:

Error from the client browser:

XMLHttpRequest 无法加载 http://example.com:9090/api/sync.这Access-Control-Allow-Origin"标头有一个值'http://example.com:5001' 不等于提供的来源.因此,不允许访问 Origin 'http://example.com:9001'.

推荐答案

这是我在我的 express 应用程序中使用的,以允许多个来源

Here is what I use in my express application to allow multiple origins

app.use((req, res, next) => {
  const allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
       res.setHeader('Access-Control-Allow-Origin', origin);
  }
  //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.header('Access-Control-Allow-Credentials', true);
  return next();
});

这篇关于在 Node.js 中为多个域启用 Access-Control-Allow-Origin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 05:41