在REQUEST Node.js中返回JSON正文 [英] Return json body in REQUEST nodejs
本文介绍了在REQUEST Node.js中返回JSON正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用request
模块向URL发出HTTP GET请求,以获取JSON响应.
I'm using the request
module to make an HTTP GET request to an url in order to get a JSON response.
但是,我的函数没有返回响应的主体.
However, my function is not returning the response's body.
有人可以帮我吗?
这是我的代码:
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()函数返回之前会调用
.
is being called before your getJson() function returns.
您可以将回调传递给getJson:
You can either pass a callback to getJson:
getJson(req.params.id, function(data) {
res.json(data);
});
...并且在getjson函数中:
...and in the getjson function:
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));
这篇关于在REQUEST Node.js中返回JSON正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文