【问题标题】:resend response after request.end()在 request.end() 之后重新发送响应
【发布时间】:2023-03-09 13:25:01
【问题描述】:

我在编写正确的回调时遇到了困难。 当用户向“/city”服务器发出请求时,必须向第三方服务请求查询数据。为此,我执行 http.request() 来请求和接收数据(没有问题)。然后我需要将数据传输到 getCity() 函数之外的 res.send() 中。

我不知道。请解释一下解决方案和工作原理。谢谢!

var getCity = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
      //what to do?
  });
}

app.get('/city', function (req, res) {
    var request = http.request(options, getCity);
    request.end();  
    res.send("ok"); //need sending str from getCity instead of "ok";
});

【问题讨论】:

    标签: javascript node.js http express


    【解决方案1】:

    我会推荐使用以下方法来做一些解决类型的任务,

    var cityDecorator = function(req,res,next) {
      var str = ''
      http.request(options, function(response){
        response.on('data', function (chunk) {
          str += chunk;
        });
    
        response.on('end', function () { 
            req.params.cityValue = str; // N1
            next(); // N2
        });
      }).end();
    }
    
    app.get('/city',cityDecorator, function (req, res) {
        res.send(req.params.cityValue);
    });
    

    N1 :您只能从该行发送响应,但我更喜欢并建议仅从一个文件发送响应,因此将来如果您想更改 res,或想要装饰,或渲染或其他什么,您只需处理一个文件,即你的路由文件。

    这仅在您使用 express 时才有效,从您的代码看起来像您所做的那样,但如果没有然后评论,我将为该场景提供解决方案。 总账

    【讨论】:

    • 哇,它有效!但我不明白“next()”是如何工作的...... app.get() 看起来像 app.get('/city', callback(req, res, next) [,callback(req, res, next)。 ..]) 当“下一个”调用新回调时?
    • 它被称为Router级别的中间件,所以它会跳转到下一个回调函数,或者如果没有定义回调函数,则会触发匹配路由。在这里阅读更多:expressjs.com/guide/using-middleware.html#middleware.router
    • 嗯,这就是我需要的!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多