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

I have a lengthy process that needs to send data in multiple steps. Is there a way to post 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 ishello

How can I post multiple responses or is it not possible with an expression?

+3


source to share


3 answers


Use res.write()

.



res.send()

already makes a call res.end()

, which means you can no longer write to res after calling res.send (which means your call is res.end()

useless).

+9


source


You can only send one HTTP response for one HTTP request. However, you can of course write any data in the response you want. It can be JSON with multiple characters, multipart parts, or whatever format you choose.



If you want to send events from the server to the browser, a simple alternative would be to use something like Server-sent events ( polyfill ).

+1


source


Try this, it should fix 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();
});

      

+1


source







All Articles