【问题标题】:CORS error with socket.io using Nginx使用 Nginx 的 socket.io 出现 CORS 错误
【发布时间】:2019-02-02 22:09:32
【问题描述】:

在 Ubuntu 中出现 CORS 与 nginx 代理的套接字连接错误,而 Http 请求可以正常工作。

这是我的 Nginx 配置文件。此配置适用于 Windows 和 Mac,但不适用于 Ubuntu。

server 
{
    listen 7000 default_server;
    listen [::]:7000 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name localhost;
    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
             proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_http_version 1.1;
            proxy_set_header X-Forwarded-For 
            $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_pass http://nodes;
    }
}

upstream nodes {
    # enable sticky session based on IP
    ip_hash;

    server localhost:3000;
    server localhost:3001;
    server localhost:3003;
}

【问题讨论】:

标签: node.js nginx socket.io cors


【解决方案1】:
server{
        listen 7000;
        server_name www.whatever.com;
        location / {
                add_header 'Access-Control-Allow-Origin' 'http://localhost:7000' always;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
                add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin,x-auth' always;
                default_type application/json;
                proxy_pass //node;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;





    }


}

这可能会有所帮助并将地址替换为适当的地址。

【讨论】:

  • 执行您建议的代码后产生了一个新错误。它已经解决了之前的错误。新错误是:“‘Access-Control-Allow-Origin’标头的值‘localhost:7000’不等于提供的原点。因此,原点‘null’不允许访问。”您能帮我如何更改供应来源吗?
  • 你在哪个端口上运行你的服务器?是 7000 吗?
  • @SwatiMavani 您评论中引用的错误消息似乎表明您现在正在通过从本地计算机上的文件运行前端代码进行测试。您需要通过在 Web 服务器上运行它来测试它
  • @sideshowbarker 是对的。请尝试通过在 Web 服务器上运行来测试它。
猜你喜欢
  • 2017-11-30
  • 2015-07-17
  • 1970-01-01
  • 2021-10-07
  • 2019-11-09
  • 2021-05-28
  • 2020-03-13
  • 2015-06-24
  • 2021-09-21
相关资源
最近更新 更多