【问题标题】:WebSocket error, Unexpected response code: 200 with Nginx and Node.jsWebSocket 错误,意外响应代码:200 与 Nginx 和 Node.js
【发布时间】:2019-11-24 06:19:45
【问题描述】:

我在 DigitalOcean 上使用 Ubuntu 服务器来托管 Nginx Web 服务器和运行 WebSocket 服务器的 Node 应用程序。尝试连接到服务器的 IP 时,我在控制台中收到以下消息:

WebSocket connection to 'ws://<server's public IP>' failed: Error during WebSocket handshake: Unexpected response code: 200

我设置 Nginx 所做的只是关注this guide,它只是告诉你安装 Nginx 并调整 UFW 防火墙。我在第 4 步中没有设置服务器块,也没有触及任何其他配置文件。

之后,我将我的index.htmlclient.js 文件放在/var/www/html 目录中,由Nginx 提供服务。

index.html 是一个运行client.js 的非常简单的HTML 页面。该 JS 文件如下所示:

const ws = new WebSocket('ws://<public IP, same as above>:80');

ws.addEventListener('open', () => {
    const json = { message: 'hello from client!' };
    const jsonString = JSON.stringify(json);
    ws.send(jsonString);
});

ws.addEventListener('message', event => {
    const data = JSON.parse(event.data);
    console.log(data);
});

服务端 Node 应用是websocket.js,它看起来像这样:

const buffer = require('buffer');
const http = require('http').createServer();
const ws = require('ws');
const wsServer = new ws.Server({ server: http });

wsServer.on('connection', (socket) => {
    socket.on('message', (msg) => {
        console.log('received: ' + msg);
        socket.send(Buffer.from('hello from the server!'));
    });

    const json = { message: 'hello from server!' };
    const jsonString = JSON.stringify(json);
    socket.send(Buffer.from(jsonString));
});

http.listen(8080, () => console.log('listening on 8080'));

此文件与node_modulespackage.jsonpackage-lock.json 一起放置在/root。将它与/var/www/html 的客户端代码一起提供并没有帮助。当然,它也是通过 PM2 运行的,我也尝试在没有 PM2 的情况下运行。

感谢您的帮助,如果有任何我可能遗漏的信息,请告诉我。

【问题讨论】:

    标签: node.js nginx websocket


    【解决方案1】:

    为了让 Nginx 和 Node.js 正常运行,您需要采取一些额外的步骤。

    我去了/etc/nginx/sites-available/default并更新了这个块:

    location / {
        try_files $uri $uri/ =404;
    }
    

    到这个块:

    location / {
        proxy_pass http://localhost:8080;  # change to your port if needed
        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;
        try_files $uri $uri/ =404;
    }
    

    然后更新我的 Node 应用程序以使用 app.use(express.static('/var/www/html')); 通过 Express 提供文件。

    这里有几个链接帮助我找到了正确的答案:

    Node.js + Nginx - What now?

    https://www.digitalocean.com/community/questions/how-to-run-node-js-server-with-nginx

    我发现了一个额外的链接,它告诉你更多关于使用的 Nginx 指令:

    http://nginx.org/en/docs/http/ngx_http_proxy_module.html

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 2014-09-21
      • 1970-01-01
      • 2020-03-11
      • 2020-09-19
      相关资源
      最近更新 更多