我无法在Express服务器上创建Websocket连接。我在这个问题上进行了很多搜索,但找不到任何解决方案。我的代码如下:
const express = require('express');
const cors = require('cors');
const http = require('http');
const mongoose = require('mongoose');
const ws = require('ws');
const app = express();
// CORS
app.use(cors({ origin: true, credentials: true }));
app.options("*", cors({ origin: true, credentials: true }));
const httpServer = http.createServer(app);
const websocketServer = new ws.Server({ server: httpServer })
websocketServer.on('connection', (websocket, req) => {
console.log('connected');
})
const server = app.listen(3000, () => {
mongoose.connect(`mongodb://localhost:27017/quizzer`,
{ useUnifiedTopology: true, useNewUrlParser: true }, () => {
console.log(`Serverstarted on port ${server.address().port}`);
});
});
服务器已启动并且正在侦听端口3000。但是仍然出现以下错误:
WebSocket connection to 'ws://localhost:3000/' failed: Error during WebSocket handshake: Unexpected response code: 404