20

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?

1

4 Answers 4

33

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

Sign up to request clarification or add additional context in comments.

10 Comments

I can't find that function in the documentation and it doesn't seem to be working for me.
It is not from express, but directly from Node.js. It is the low level function. What do you try to achieve ? This should work as expected for the example you described ahead, I just tried it in local.
@aydow Links or it did not happened
@aydow res.write() is a Node.js function, see the documentation here
@aydow res.write() isn't deprecated. I suggest removing your comment lest it mislead someone.
|
8

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).

1 Comment

I think this should really be the accepted answer. The main point, as you say, is that 'You can only send one HTTP response for one HTTP request.' I think the questioner is asking for something like streaming, rather than the ability to write() repeatedly before calling send().
2

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();
});

Comments

0
res.write(JSON.stringify({
    min, 
    max, 
    formattedData
}));

or

res.send({
    min,
    max,
    formattedData
});

refer Node Res.write send multiple objects:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.