Hir*_*del 3 javascript json httprequest node.js
我正在使用该request模块向URL发出HTTP GET请求以获取JSON响应.
但是,我的功能不是返回响应的正文.
有人可以帮我这个吗?
这是我的代码:
router.get('/:id', function(req, res) {
var body= getJson(req.params.id);
res.send(body);
});
Run Code Online (Sandbox Code Playgroud)
这是我的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);
})
}
Run Code Online (Sandbox Code Playgroud)
res.send(body);
Run Code Online (Sandbox Code Playgroud)
在getJson()函数返回之前调用.
您可以将回调传递给getJson:
getJson(req.params.id, function(data) {
res.json(data);
});
Run Code Online (Sandbox Code Playgroud)
...并在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);
})
}
Run Code Online (Sandbox Code Playgroud)
或者直接致电:
res.json(getJson(req.params.id));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23960 次 |
| 最近记录: |