在 Node.js 中为多个域启用访问控制-允许-起源

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

规范还说我不能为 Access-Control-Allow-Origin做数组或逗号分隔值,建议的方法是做类似于这个 访问控制-允许起源多起源域? ?的事情

但是在 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");

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

XMLHttpRequest 无法加载 http://example.com:9090/api/sync “访问控制-允许-起源”标头有一个值 不等于所提供的原产地的「 http://example.com:5001」。 因此,原产地「 http://example.com:9001」不能进入。

90981 次浏览

Not sure if this is to late but I solved it by setting: res.setHeader("Access-Control-Allow-Origin", req.headers.origin);

This will simply allow every connection as the headers.origin will be sent with every query.

You may want to write a function to check if the req.headers.origin is a whitelisted domain (from a hardcoded array) and the simply return this domain if it exists in the array.

Check your whitelist against what your req.headers.origin e.g.

var origins = ['a.com', 'b.com', 'c.com', 'boobies.com'];
for(var i=0;i<origins.length;i++){
var origin = origins[i];
if(req.headers.origin.indexOf(origin) > -1){
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
return;
}
// else, tough cookies.
}

Enjoy.

Here's a simple middleware function to serve up the correct CORS header from a whitelist. Setting this near the top of your express app will allow all your routes to set the proper header from the whitelist before serving up content.

app.use(function(req, res, next){
var whitelist = ['localhost:4000', 'localhost:3000', 'anydomain.com']
var host = req.get('host');


whitelist.forEach(function(val, key){
if (host.indexOf(val) > -1){
res.setHeader('Access-Control-Allow-Origin', host);
}
})


next();
});

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();
});