Nginx + NodeJS + Socket.IO-'Access-Control-Allow-Origin'标头包含多个值'*,*',但只允许一个

时间:2019-08-12 10:24:04

标签: node.js nginx socket.io

我在NodeJS + Express + Nginx上的Socket.IO遇到问题。

我已经启动服务器并像这样连接Socket

var server = https.createServer(options, app).listen(4306);
io = require('socket.io').listen(server);
io.origins((origin, callback) => {
    if (["....."].indexOf(origin) < 0) { //..... are the allowed origins
        return callback('Origin not allowed', false);
    }
    callback(null, true);
});

Nginx的配置如下

server {
    listen 4305 default_server ssl http2;
    server_name api.myservername.com;
    #rewrite_log on;

    location / {
        set $cors '';

        if ($http_origin ~* (.....) {
            set $cors 'on';
        }

        if ($request_method = OPTIONS) {
            set $cors "${cors}_options";
        }

        # Allow CORS on preflight request
        if ($cors = 'on_options') {
            add_header 'Content-Length' 0 always;
            add_header 'Content-Type' 'text/plain; charset=utf-8' always;
            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, OPTIONS' always;
            add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;
            return 204;
        }

        proxy_pass  https://127.0.0.1:4306$uri$is_args$args;

        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;

        # Allow CORS on other requests after returning from the upstreams
        if ($cors = 'on') {
            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, OPTIONS' always;
            add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;
        }
    }

对API的HTTP调用工作正常,但是套接字连接和轮询会返回以下错误

The 'Access-Control-Allow-Origin' header contains multiple values 'https://myserver.com, https://myserver.com', but only one is allowed.

你能帮我吗?

0 个答案:

没有答案