简体   繁体   English

在 Express.js 中使用相同的响应对象发送多个响应

[英]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有没有办法用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但是当我运行curl -X POST localhost:3001/helloworld我得到的只是hello

How can I send multiple responses or is this not possible to do with express?我如何发送多个回复,或者这与快递无关?

Use res.write() .使用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). res.send()已经调用res.end() ,这意味着在调用 res.send 之后你不能再写 res (这意味着你的res.end()调用也没有用)。

EDIT: It is a Node.js internal function.编辑:它是一个 Node.js 内部函数。 See the documentation here 请参阅此处的文档

You can only send one HTTP response for one HTTP request.您只能为一个 HTTP 请求发送一个 HTTP 响应。 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.这可以是换行符分隔的 JSON、多部分部分或您选择的任何其他格式。

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 ).如果您想将事件从服务器流式传输到浏览器,一个简单的替代方法可能是使用诸如服务器发送的事件( polyfill ) 之类的东西。

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();
});
res.write(JSON.stringify({
    min, 
    max, 
    formattedData
}));

or或者

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

refer Node Res.write send multiple objects:参考Node Res.write 发送多个对象:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM