简体   繁体   English

CORS 与 Express、Socket.io 和 Nginx 问题

[英]CORS issues with Express, Socket.io and Nginx

I have adapted a tutorial to get a simple Socket.io chat going in Node.我已经改编了一个教程,以在 Node.js 中进行简单的 Socket.io 聊天。 It works when hosted locally, but after pushing it to a test server I can't get the socket connection to be accepted.它在本地托管时有效,但在将其推送到测试服务器后,我无法接受套接字连接。 Seems to be a cross-origin related matter, though I'm slightly confused about how to route things in Nginx also.似乎是与跨域相关的问题,尽管我对如何在 Nginx 中路由事物也有些困惑。 Following the advice in the related questions hasn't helped.遵循相关问题中的建议没有帮助。

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

Index.js:索引.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 sites-available: 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/;
    }
}

Any insights welcome!欢迎任何见解!

Hope this will help with all the CORS error希望这将有助于解决所有 CORS 错误

Because it will handle it for you因为它会为你处理

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

Docs CORS文档CORS

Making this change fixed the issue:进行此更改解决了问题:

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

This way uses the default connection destination with socket.这种方式使用带有套接字的默认连接目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM