【问题标题】:Return json body in REQUEST nodejs在请求 nodejs 中返回 json 正文
【发布时间】:2014-11-03 19:52:55
【问题描述】:

我正在使用 request 模块向 url 发出 HTTP GET 请求以获取 JSON 响应。

但是,我的函数没有返回响应的正文。

有人可以帮我解决这个问题吗?

这是我的代码:

router.get('/:id', function(req, res) {
  var body= getJson(req.params.id);
  res.send(body);
});

这是我的getJson 函数:

function getJson(myid){
  // Set the headers
  var headers = {
   'User-Agent':       'Super Agent/0.0.1',
   'Content-Type':     'application/x-www-form-urlencoded'
  }
  // Configure the request
  var options = {
    url: 'http://www.XXXXXX.com/api/get_product.php',
    method: 'GET',
    headers: headers,
    qs: {'id': myid}
  }

  // Start the request
  request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    return body;
  }
  else
    console.log(error);
  })
}

【问题讨论】:

  • 而你的 get_product.php 实际上输出的是 JSON,对吧?
  • 您是否针对另一个已知的类似服务测试了此代码?
  • @chris-l 当我写 console.log(body) 而不是返回正文时;它在我的日志中显示 json 数据
  • @tadman 当我在浏览器中尝试时,该 URL 有效
  • @HiradRoshandel 除非您要部署浏览器,否则您需要测试您的 NodeJS 代码。您在这里所拥有的应该工作。

标签: javascript json node.js httprequest


【解决方案1】:
res.send(body); 

在您的 getJson() 函数返回之前被调用。

您可以将回调传递给 getJson:

getJson(req.params.id, function(data) {
    res.json(data);
});

...在getjson函数中:

function getJson(myid, callback){
// Set the headers
var headers = {
'User-Agent':       'Super Agent/0.0.1',
'Content-Type':     'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://www.XXXXXX.com/api/get_product.php',
method: 'GET',
headers: headers,
qs: {'id': myid}
}

// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
    callback(body);
}
else
    console.log(error);
})  

}

或者直接调用:

res.json(getJson(req.params.id));

【讨论】:

  • 非常感谢。我还将这一行 callback(body) 更改为 callback(JSON.parse(body))。
【解决方案2】:

问题是你正在做一个返回,期望路由器会得到内容。

由于是异步回调,因此无法正常工作。您需要将代码重构为异步。

当你在做return body; 的时候,返回的函数是请求的回调函数,并且在任何情况下你都没有将body 发送到路由器。

试试这个:

function getJson(myid, req, res) {
  var headers, options;

  // Set the headers
  headers = {
    'User-Agent':       'Super Agent/0.0.1',
    'Content-Type':     'application/x-www-form-urlencoded'
  }

  // Configure the request
  options = {
    url: 'http://www.XXXXXX.com/api/get_product.php',
    method: 'GET',
    headers: headers,
    qs: {'id': myid}
  }

  // Start the request
  request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      res.send(body);
    } else {
      console.log(error);
    }
  });
}

还有这个路由器:

router.get('/:id', function(req, res) {
  getJson(req.params.id, req, res);
});

在这里,您将res 参数传递给getJson 函数,因此request 的回调将能够尽快调用它。

【讨论】:

  • 那我怎样才能将body返回给路由器呢?我试过了,但它不起作用: var callback=request(....) return callback;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
相关资源
最近更新 更多