Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending multiple responses with the same response object in Express.js

I have a long running process which needs to send data back at multiple stages. Is there some way to send back multiple responses with express.js

res.send(200, 'hello')
res.send(200, 'world')
res.end() 

but when I run curl -X POST localhost:3001/helloworld all I get is hello

How can I send multiple responses or is this not possible to do with express?

like image 591
Loourr Avatar asked Aug 08 '14 17:08

Loourr


People also ask

Can I send multiple responses for a single request in Nodejs?

You can only send one HTTP response for one HTTP request.

Can I send multiple responses for a single request?

No. In http, one request gets one response. The client must send a second request to get a second response.

How do you send a response back to a client in node JS?

Methods to send response from server to client are:Using send() function. Using json() function.


3 Answers

Use res.write().

res.send() already makes a call to res.end(), meaning you can't write to res anymore after a call to res.send (meaning also your res.end() call was useless).

EDIT: It is a Node.js internal function. See the documentation here

like image 133
yachaka Avatar answered Oct 05 '22 06:10

yachaka


You can only send one HTTP response for one HTTP request. However, you can certainly write whatever kind of data in the response that you want. That could be newline-delimited JSON, multipart parts, or whatever other format you choose.

If you want to stream events from the server to the browser, an easy alternative might be to use something like Server-sent events (polyfill).

like image 30
mscdex Avatar answered Oct 05 '22 04:10

mscdex


Try this, this should solve your problem.

app.get('/', function (req, res) {

  var i = 1,
    max = 5;

  //set the appropriate HTTP header
  res.setHeader('Content-Type', 'text/html');

  //send multiple responses to the client
  for (; i <= max; i++) {
    res.write('<h1>This is the response #: ' + i + '</h1>');
  }

  //end the response process
  res.end();
});
like image 38
patz Avatar answered Oct 05 '22 06:10

patz