我已经多次看到这个问题,但我觉得我的用例没有完全解决,所以我将它发布在下面:
尝试连接到我的 websocket 时出现此错误:
scripts.js:44 WebSocket connection to 'ws://localhost:3000/' failed: Error during WebSocket handshake: Unexpected response code: 200
有一个小变化使它失败与成功。见下文:
服务器.js:
'use strict';
const express = require('express');
const WebSocket = require('ws');
const PORT = process.env.PORT || 3000;
// Failing:
const server = express().use(express.static('public'));
server.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});
server.listen(PORT, () => {
console.log(`Example app listening on PORT ${PORT}!`)
});
///
// Working (no websocket connection issues):
///const server = express().use(express.static('public'))
// .listen(PORT, () => {
// console.log(`Example app listening on PORT ${PORT}!`)
// });
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
console.log(ws);
ws.on('message', function incoming(message) {
console.log('received message: %s', message);
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
相关:客户代码:
var HOST = location.origin.replace(/^http/, 'ws');
var socket = new WebSocket(HOST); //this is the line where the connection is attempted.
在 localhost、ngrok 上运行或部署到 heroku 似乎没有什么区别,除非我错过了什么......
我尝试了其他帖子中的各种方法,但无济于事。他们提到了更改网络配置(似乎与我的使用无关),或各种配置 express js 的方法,但它们没有帮助。这实际上只是上面代码中的微小变化。websocket 是否命中 GET 路由?