【问题标题】:unable to capture context in node.js无法在 node.js 中捕获上下文
【发布时间】:2015-12-29 05:39:09
【问题描述】:

我试图了解闭包在 node.js 中是如何工作的

我有一个快速中间件,用于抓取远程站点 (*json) 的内容。这里的情况是我无法使用远程内容更新快速请求(我认为这是可能的)以在其他中间件中进一步处理它。

欢迎任何帮助:)

问候

    const request = require('request');
    const app = require('express')();
    const base = { url: 'http://api.xxx', record: 'todo' };

    function getFile(opts, cb) { // parse url using request
      request({
        url: opts.url,
        headers: {
            'User-Agent': 'request',
            'Content-type': 'application/json'
        }
      }, function (error, response, body) {
        if (error || response.statusCode != 200) {
            cb(error);
        } else {
            var ret = {content: JSON.parse(body), request: opts}
            cb(null, ret);
        }
      });
    }

    function grabData(req, res, next) {
    console.log(new Date(), req.method, req.url);
      getFile(base, function(err, data){

        console.log(data.content); // WORKS OK!

        //? How to get data.content injected in the request
        // req.contents = data.content // not working

           next();
      });

    }

// function calls ---------------------

app.use(grabData);

//app.use(furtherProcess)  //? how to pass args here?

app.get('/',  function(req,res){
    res.send("> "+req.contents);
    res.end();
});

app.listen(3000, function(){ console.log('Listen on port 3000...' ); });

【问题讨论】:

  • 尝试使用 req.pipe ,所以可能是这样的: req.get(opt.url).pipe(res) ?

标签: javascript node.js asynchronous express


【解决方案1】:

我在您的中间件中没有看到对 next() 的任何调用。修改req对象后需要调用next()

function grabData(req, res, next) {
  getFile(base, function(err, data){
    req.contents = data;
    next();
  })
}

【讨论】:

  • 抱歉,我无法粘贴完整的内容,所以我分部分粘贴了,我忘记了:) 仍然不行(我已经用下一个更正了)
  • 将您的 next() 调用移到 getFile callback() 中,因为它是异步的。
猜你喜欢
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多