节点+ socket.io与nginx正确设置

时间:2017-12-04 22:48:01

标签: javascript node.js nginx socket.io virtualhost

我从node.js获得了简单的站点,它将消息发送到socket.io(它在同一个node.js实例上运行)。在localhost上一切正常但是当我尝试在vps上设置nginx时,问题就开始了,客户端无法找到我的socket.io端点。

https://example.com - socket.io client

https://example.com/sender - socket.io server

请记住,来自其他域的客户端也必须能够使用socket.io端点。

节点应用

const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const port = 8080;

app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept-Type');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

app.listen(port, () => {
    console.log("Server is running on port: " + port);
});

server.listen(4200);

app.get('/', (req, res) => {
    res.render('index');
});

io.on('connection', (client) => {
    console.log('Client connected...');

    client.on('messages', (data) => {
        client.emit('reply', data);
    });
});

nginx配置:

 server {
    listen 80;
    listen [::]:80;

    root /home/project_path/;
    server_name example.com;

    if ($scheme != "https") {
      return 302 https://$host$request_uri;
    } # managed by Certbot

    location /sender {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://localhost:4200;
      proxy_redirect off;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }

    location / {
      proxy_pass http://localhost:8080;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com-
    0001/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com-
    0001/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  }

1 个答案:

答案 0 :(得分:1)

  

使用nginx的Node + socket.io正确设置:)?

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    root         /usr/share/nginx/html;

    location /socket.io/ {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_pass http://localhost:2156/socket.io/;
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}
  

客户端套接字网址:http://localhost/socket.io/