【问题标题】:Sending multiple responses with the same response object in Express.js在 Express.js 中使用相同的响应对象发送多个响应
【发布时间】:2014-08-08 17:32:16
【问题描述】:

我有一个长时间运行的进程,需要在多个阶段发回数据。有没有办法用express.js发回多个回复

res.send(200, 'hello')
res.send(200, 'world')
res.end() 

但是当我运行curl -X POST localhost:3001/helloworld 时,我得到的只是hello

我怎样才能发送多个回复,或者这不能用快递做?

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    使用res.write()

    res.send() 已经调用了res.end(),这意味着在调用 res.send 之后你不能再写 res(这意味着你的res.end() 调用也没有用)。

    编辑:这是一个 Node.js 内部函数。 See the documentation here

    【讨论】:

    • 我在documentation 中找不到该功能,而且它似乎对我不起作用。
    • 不是来自express,而是直接来自Node.js。它是低级功能。你想达到什么目的?对于您前面描述的示例,这应该可以按预期工作,我只是在本地尝试过。
    • res.write() 从 express 3.x 开始似乎已被弃用
    • @aydow 链接或它没有发生
    • @aydow res.write() 是一个 Node.js 函数,see the documentation here
    【解决方案2】:

    您只能为一个 HTTP 请求发送一个 HTTP 响应。但是,您当然可以在响应中写入您想要的任何类型的数据。这可以是换行符分隔的 JSON、多部分或您选择的任何其他格式。

    如果您想将事件从服务器传输到浏览器,一个简单的替代方法可能是使用 Server-sent events (polyfill) 之类的东西。

    【讨论】:

      【解决方案3】:

      试试这个,这应该可以解决你的问题。

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

      【讨论】:

        【解决方案4】:
        res.write(JSON.stringify({
            min, 
            max, 
            formattedData
        }));
        

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

        参考Node Res.write send multiple objects:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-05-27
          • 1970-01-01
          • 2021-04-20
          • 2015-04-23
          • 2018-08-19
          • 1970-01-01
          • 2021-12-22
          • 1970-01-01
          相关资源
          最近更新 更多