user3094755
user3094755

Reputation: 1641

Nuxt JS with WebSockets

I have a Nuxt App, with one service which needs to be delivered over WebSockets. The Nuxt App Server provides an api service using express.

I have an /api folder in which there are various *.js files, and these are routed to successfully. ie...

const express = require('express');
const app = express();

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

works OK.

However the following, in the same file, will never be reached....

const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);

app.ws('/whatever2',(ws,req) => {
    console.log('req.url',req.url);
})

Where am I going wrong ?

Upvotes: 2

Views: 3584

Answers (1)

msafi
msafi

Reputation: 377

You're attempting to connect the client to an endpoint on the server where no such endpoint exists. In your client's output, you're receiving an error of:

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

because you haven't defined a route of /api/whatever2. Your code above routes to:

 ws://localhost:3000/whatever2

instead of ws://localhost:3000/api/whatever2

EDIT:

Here's test code that worked for me:

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...'));

Upvotes: 1

Related Questions