Why can't we do multiple response.send in Express.js?

后端 未结 2 2091
萌比男神i
萌比男神i 2020-12-08 10:01

3 years ago I could do multiple res.send in express.js.
even write a setTimeout to show up a live output.

response.send(\'

        
相关标签:
2条回答
  • 2020-12-08 10:09

    response.send sends an entire HTTP response to the client, including headers and content, which is why you are unable to call it multiple times. In fact, it even ends the response, so there is no need to call response.end explicitly when using response.send.

    It appears to me that you are attempting to use send like a buffer: writing to it with the intention to flush later. This is not how the method works, however; you need to build up your response in code and then make a single send call.

    Unfortunately, I cannot speak to why or when this change was made, but I know that it has been like this at least since Express 3.

    0 讨论(0)
  • 2020-12-08 10:28

    Maybe you need: response.write

    response.write("foo");
    response.write("bar");
    //...
    response.end()
    

    res.send implicitly calls res.write followed by res.end. If you call res.send multiple times, it will work the first time. However, since the first res.send call ends the response, you cannot add anything to the response.

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