WebSocket错误,意外的响应代码:使用Nginx和Node.js时出现200

时间:2019-11-24 06:19:45

标签: node.js nginx websocket

我在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'));

此文件与/rootnode_modulespackage.json一起放在package-lock.json。与/var/www/html的客户端代码一起提供服务没有帮助。当然,感谢PM2,它也可以运行,我也尝试了不使用PM2的情况,这没有什么区别。

我们非常感谢您的帮助,如果有任何我想念的信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

结果证明,您需要执行一些额外的步骤才能使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