[英]Return json body in REQUEST nodejs
我正在使用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);
})
}
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));
問題是你正在做回報,期望路由器獲得內容。
由於是異步回調,因此不起作用。 您需要將代碼重構為異步。
當你做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
函數,因此請求的回調將能夠在它能夠執行時立即調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.