Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!