带WebSocket的Nuxt JS

时间:2018-10-07 18:49:34

标签: javascript node.js nuxt.js

我有一个Nuxt应用程序,其中一项服务需要通过WebSocket交付。 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);
})

我要去哪里错了?

1 个答案:

答案 0 :(得分:0)

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

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...'));
相关问题