Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda