Nuxt JS with WebSockets



我有一个Nuxt应用程序,其中一项服务需要通过WebSockets交付。 Nuxt App Server 使用 express 提供 API 服务。

我有一个/api 文件夹,其中有各种 *.js 文件,这些文件已成功路由到。

const express = require('express');
const app = express();
app.get('/whatever1',(req, res) => console.log('req.url',req.url))

工作正常。

但是,在同一文件中,将永远无法访问以下内容。

const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
app.ws('/whatever2',(ws,req) => {
console.log('req.url',req.url);
})

我哪里做错了?

你正在尝试将客户端连接到服务器上不存在此类终结点的终结点。在客户端的输出中,您收到以下错误:

VM1295:1 WebSocket connection to 'ws://localhost:3000/api/whatever2' failed: Connection closed before receiving a handshake response

因为您尚未定义/api/whatever2 的路由。上面的代码路由到:

ws://localhost:3000/whatever2

而不是ws://localhost:3000/api/whatever2

编辑:

这是对我有用的测试代码:

const express = require('express');
var app = express();
const expressWS = require('express-ws')(app);
expressWS.getWss().on('connection', function (ws) {
console.log('connection open');
});
app.ws('/whatever', (ws, res) => {
console.log('socket', ws);
});
app.listen(3000, () => console.log('listening on 3000...'));

最新更新