【问题标题】:CORS issues with Express, Socket.io and NginxExpress、Socket.io 和 Nginx 的 CORS 问题
【发布时间】:2021-04-10 06:07:41
【问题描述】:

我已经改编了一个教程,以便在 Node.js 中进行简单的 Socket.io 聊天。它在本地托管时有效,但在将其推送到测试服务器后,我无法接受套接字连接。似乎是一个与跨域相关的问题,尽管我对如何在 Nginx 中路由事物也有些困惑。遵循相关问题中的建议没有帮助。

客户端脚本: var socket = io.connect('http://localhost/socket.io');

Index.js:

const express = require('express');
const app = express();
const path = require('path');
const httpServer = require('http').createServer(app);
const io = require('socket.io')(httpServer, {
    cors:true,
    origins:["*"],
    // origins:["http://xxx.xxx.xxx.xxx:8080"],
    // transports: ['websocket'],
});


const views_path = (__dirname + '/views');

app.set('views',views_path);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
    console.log('render request received');
    res.render('startPage.ejs');
});

io.sockets.on('connection', socket => {
    console.log('connection received.')
    socket.on('username', function(username) {
        socket.username = username;
        io.emit('is_online', socket.username);
    });
    //...
});

httpServer.listen(8080);

nginx 站点可用:

server {
    server_name campfire;
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/campfire/html;

    index index.html index.htm index.nginx-debian.html;

    location ^~ /assets/ {
        gzip_static on;
        expires 12h;
        add_header Cache-Control public;
    }

    location / {
        proxy_set_header Host $host;
        #proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:8080;
    }
    location /socket.io/ {
            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://localhost:8080/socket.io/;
    }
}

欢迎任何见解!

【问题讨论】:

    标签: node.js express sockets nginx cors


    【解决方案1】:

    进行此更改解决了问题:

    客户端脚本: var socket = io.connect();

    这种方式使用带有套接字的默认连接目的地。

    【讨论】:

      【解决方案2】:

      希望这将有助于解决所有 CORS 错误

      因为它会为你处理它

      const cors = require('cors');
      app.use(cors());
      

      文档CORS

      【讨论】:

      • 您好,感谢您的回答。可悲的是,我已经尝试过了,但它没有解决任何问题。
      猜你喜欢
      • 2019-01-12
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 2021-03-17
      相关资源
      最近更新 更多