CORS问题:“ Access-Control-Allow-Origin”标头不得包含多个值 [英] CORS issues: The 'Access-Control-Allow-Origin' header mustn't contain multiple values

查看:808
本文介绍了CORS问题:“ Access-Control-Allow-Origin”标头不得包含多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想允许我的服务器允许两个不同的域读取数据而不会出现CORS问题。

I want to allow my server to let two different domains read data without getting a CORS issue.

因此,我在node.js中编写了以下代码行:

Therefore, I wrote the following code line (in node.js):

app.use(function(req, res, next){
   res.header("Access-Control-Allow-Origin", ["http://ServerA:3000", "http://ServerB:3000"]);
   res.header("Access-Control-Allow-Headers", "*");
   next();
});

但是,当我通过浏览器发送请求时,出现错误:

However, when I sent the request by the browser I got the error:


'Access-Control-Allow-Origin'标头包含多个值
' http:// ServerA:3000 http:// ServerB:3000 ',但仅限一个是允许
。因此,不允许
访问源' http:// ServerB:3000

The 'Access-Control-Allow-Origin' header contains multiple values 'http://ServerA:3000, http://ServerB:3000', but only one is allowed. Origin 'http://ServerB:3000' is therefore not allowed access.

我的问题是如何为多个来源定义 Access-Control-Allow-Origin。我不想使用 *,因为它太宽松了。

My question is how to define 'Access-Control-Allow-Origin for more than one origin. I don't want to use '*' because it is too liberal.

推荐答案

您需要使用配置文件中的内容检查当前来源:

You need to check your current origin with the ones that you have in the config:

let allowedOrigins = ["http://ServerA:3000", "http://ServerB:3000"]
let origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
    res.header("Access-Control-Allow-Origin", origin); // restrict it to the required domain
}

标头只期望起源或通配符,这就是为什么它对您不起作用的原因

The header expects only one value of the origin, or a wildcard sign, that's why it's not working for you

这篇关于CORS问题:“ Access-Control-Allow-Origin”标头不得包含多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆