在REQUEST nodejs中返回json体

我正在使用request模块对URL进行HTTP GET请求以获得JSON响应。

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

有人可以帮我这个吗?

这是我的代码:

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

 res.send(body); 

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

你可以传递一个callbackgetJson:

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

问题是,你正在做一个回报,期待路由器将获得内容。

由于是asynchronouscallback,这是行不通的。 你需要重构你的代码是asynchronous的。

当你在做return body; 正在返回的函数是请求的callback函数,并且没有任何部分是将主体发送给路由器。

尝试这个:

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

在这里,您将resparameter passing给getJson函数,所以请求的callback将能够尽快调用它。