我有一个长时间运行的进程,需要在多个阶段发送数据。是否有某种方法可以使用express.js发送多个响应?
res.send(200, 'hello')
res.send(200, 'world')
res.end()
但是当我运行curl -X POST localhost:3001/helloworld
时,我只得到了hello
我该如何发送多个响应,或者这在express中不可能实现?
我有一个长时间运行的进程,需要在多个阶段发送数据。是否有某种方法可以使用express.js发送多个响应?
res.send(200, 'hello')
res.send(200, 'world')
res.end()
但是当我运行curl -X POST localhost:3001/helloworld
时,我只得到了hello
我该如何发送多个响应,或者这在express中不可能实现?
res.write()
。
res.send()
已经调用了res.end()
,这意味着在调用res.send()
后你不能再向res中写入内容(也就是你的res.end()
调用是无效的)。res.json()
而不是 res.write()
?因为我想要在同一个 API 请求中以 JSON 格式发送多个响应。 - A Kres.write()
没有过时。我建议你删除你的评论,以免误导他人。 - ggorlenapp.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
}));
或者
res.send({
min,
max,
formattedData
});