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

后端 未结 4 626
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 15:13

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(20         


        
相关标签:
4条回答
  • 2020-12-16 15:53

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

    0 讨论(0)
  • 2020-12-16 16:00

    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();
    });
    
    0 讨论(0)
  • 2020-12-16 16:06
    res.write(JSON.stringify({
        min, 
        max, 
        formattedData
    }));
    

    or

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

    refer Node Res.write send multiple objects:

    0 讨论(0)
  • 2020-12-16 16:09

    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

    0 讨论(0)
提交回复
热议问题