在REQUEST nodejs中返回json体

时间:2014-11-03 19:52:55

标签: javascript json node.js httprequest

我正在使用request模块向网址发出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);
  })
}

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

问题在于你正在做回报,期望路由器获得内容。

由于是异步回调,因此不起作用。您需要将代码重构为异步。

当您执行return 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函数,因此请求的回调将能够在能够执行时立即调用它。

相关问题