I
I
IDONTSUDO2019-12-25 11:59:58
Node.js
IDONTSUDO, 2019-12-25 11:59:58

When the connection is closed how to pass data about this event to the backend?

There is such a front.

var ws = new WebSocket('ws:localhost:4041/echo');


export const testSoket = () => {
  let userid = isAuthenticated()._id
  ws.onmessage = function(e){ console.log(e.data); };
  ws.onopen = () => ws.send("1");
  ws.onclose = () => ws.send("2");
}

And such a back on the node.
const express = require('express')
const enableWs = require('express-ws')
let port = 4041
const app = express()
enableWs(app)

app.ws('/echo', (ws, req) => {
    // console.log(ws)
    ws.on('message', msg => {
        console.log(msg)
        ws.send(msg)
    })
    ws.on('onclose',msg  => {
        console.log('WebSocket was closed',msg)
    })
})
app.listen(port, () => console.log(`Server listening on port ws:localhost:${port}!`))

I don’t understand, is the problem in the code or am I doing something that is not in the functionality?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
IDONTSUDO, 2019-12-25
@IDONTSUDO

The line from the front that attaches the JWT token to the headers.
var ws = new WebSocket('ws:localhost:4041/echo',`${jwt}`)
ws.id = req.headers['sec-websocket-key'];
id of the socket by which the connection can be recognized
ws.jwt = req.headers['sec-websocket-protocol']
jwt token
in order to recognize how unique the value is, this data is enough.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question