如何防止" Access-Control-Allow-Origin"标头包含多个值

时间:2018-02-22 07:48:44

标签: node.js nginx

这是我的Nginx CORS配置:

set $cors '';

if ($http_origin ~ '^https?://(localhost|www\.beloveddais\.com|www\.beloveddais\.com)') {
    set $cors 'true';
}


if ($cors = 'true') {
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
    # required to be able to read Authorization header in frontend
    add_header 'Access-Control-Expose-Headers' 'Authorization' always;
}

if ($request_method = 'OPTIONS') {
    # Tell client that this pre-flight info is valid for 20 days
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
    return 204;
}

if ($request_method = 'GET') {
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
}

if ($request_method = 'POST') {
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
}

在我的浏览器控制台上,我一直得到:

  

无法加载   http://beloveddais.win/socket.io/?EIO=3&transport=polling&t=M6yTqBe:   ' Access-Control-Allow-Origin'标头包含多个值   ' http://beloveddais.comhttp://beloveddais.com',但只有一个是   允许。起源' http://beloveddais.com'因此是不允许的   访问。

我需要帮助来防止这个多头的东西。这真的浪费了我的时间。

1 个答案:

答案 0 :(得分:0)

您的配置正在添加URL两次。 这是因为您的配置文件的构造。 第一次因Access-Control-Allow-Origin条件而被添加,第二次因($cors = 'true')条件而被添加。

您应该制定明确的发送标头和准备条件的政策,使它们互相排斥,因此不会多次发送标头。