node.jshttpnodejs-stream

Data handler does not fire, even though connection is made


Seeing this strange problem where no data is being received by request to http server. I am just trying to stream some JSON line by line.

const http = require('http');

// server code here:

const s = http.createServer((req, res) => {

    console.log('request received.');  // 1

    req.on('data', d => {
        console.log('hello data:',String(d)); // <--- this line needs to be visited
    });
});

s.listen(4444);


// client code below

const r = http.request({
    protocol: 'http:',
    // host: '0.0.0.0',  // default is fine
    port: 4444,
    timeout: 500
}, res => {

    // ignore
    res.on('data', d => {
        console.log('response from server:', res);
    });

});


let requestNum = 1;

(async () => {

    while (1) {

        console.log('writing:', {requestNum});

        const json = JSON.stringify({
            timeSent: Date.now(),
            requestNum: requestNum++
        });

        r.write(json + '\n');
    

        await new Promise(resolve => setTimeout(resolve, 500));

    }

})()

so this line gets hit:

console.log('request received.');  // 1

but the problem is this callback never fires:

  req.on('data', d => {
       // we never get here :(
        console.log('hello data:',String(d));
   });

cannot figure out why.


Solution

  • In your request add method please

    {
        protocol: "http:",
        // host: '0.0.0.0',  // default is fine
        port: 4444,
        timeout: 500,
        method: "POST"
    }
    

    If method is not specified it defaults to GET and usually GET has no body.