Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
How to call ws WebSocket and wait for response in Express.js?

I have setup Nodejs to serve an HttpServer using ExpressJs. I also need to use ws WebSocket in order to connect to my device for fetching data.

My attempt is now this.

import express from 'express';
import cors from 'cors';
import http from 'http';
import { WebSocketServer } from 'ws';

const app = express();

app.use(cors());

//initialize a simple http server
const httpServer = http.createServer(app);

const wsServer = new WebSocketServer({ port: 7777});

wsServer.on('connection', function connection(ws, req) {
    app.get('/', (req, res) => {
        ws.send('{"msg":"getdata"}');
        ws.on('message', function message(data) {
            data = JSON.parse(data);
            res.json(data);
        });
    });
    
    //start our server
    httpServer.listen(7778, () => {
        console.log(`Server started on port ${httpServer.address().port} :)`);
    });
});

The problem is that when the API is called more than once. An error code: 'ERR_HTTP_HEADERS_SENT' is thrown. I assume it is because the ws.on('message') is executed multiple times. So, I am trying to find a way to remove the listener but to no avail.

Is there any better way to do this? I just want to have a webserver that calls to another websocket in order to get data from a device.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

this will solve your error code: 'ERR_HTTP_HEADERS_SENT'

 wsServer.on('connection', function connection(ws, req) {
        app.get('/', (req, res) => {
    //first This
       ws.on('message', function message(data) {
                data = JSON.parse(data);
                res.json(data);
            });
    //then use this
            ws.send('{"msg":"getdata"}');
         
        });
        
        //start our server
        httpServer.listen(7778, () => {
            console.log(`Server started on port ${httpServer.address().port} :)`);
        });
    });
about 4 years ago · Juan Pablo Isaza Relatório

0

For your code example to work, message on websocket must be sent after the / request is made. Because, before that, on message handler is not registered. Also, once handling the first request successfully, you cannot send a websocket message again. Because, when you do that, the res in the message handler is already completed. So, you will get ERR_HTTP_HEADERS_SENT. Thus proved :-)

So, your API calls must be like in the following pattern

  • / Call #1

  • Websocket message #1

  • / Call #2

  • Websocket message #2

If you do so, you will not get the ERR_HTTP_HEADERS_SENT error. Because, res is send once for every / request.

about 4 years ago · Juan Pablo Isaza Relatório

0

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var timeout = require('connect-timeout');
var uuid = require('uuidv4');
var _ = require('lodash');

app.use(timeout('10s'));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

let responses = []

io.on('connection', (socket) => {
    socket.on('res', (e) => {
        var obj = _.find(responses, r => r.id === e.id);
        obj.res.send(e)
        _.remove(responses, r => r.id === e.id);
    })
})

app.get('/endpoint', (req, res) => {
    const id = uuid()
    io.emit('req', { id, ip: req.ip, header: req.headers, method: req.method });
    responses.push({ id, res })
});

http.listen(3000);

If you want over multiple instance, you can use redis pub sub.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda