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.
CodePudding user response:
The problem is this line in the client:
r.write(json '\n');
You're not sending the end header, so the request is never ended. The server keeps waiting for more data but it never arrives.
To fix this, you can either put r.end() after r.write() or you can use the request.write() method that takes a callback:
r.write(json '\n', () => {
console.log(' wrote:', json);
});
CodePudding user response:
If you want the server to receive the data before the request is ended, you'll have to use the req.write() method that takes a callback:
r.write(json '\n', () => {
console.log(' wrote:', json);
});
This will make the client write the data and then call the callback. You can use this to end the request:
r.end(() => {
console.log('request ended');
});