【发布时间】:2014-11-03 19:52:55
【问题描述】:
我正在使用 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);
})
}
【问题讨论】:
-
而你的 get_product.php 实际上输出的是 JSON,对吧?
-
您是否针对另一个已知的类似服务测试了此代码?
-
@chris-l 当我写 console.log(body) 而不是返回正文时;它在我的日志中显示 json 数据
-
@tadman 当我在浏览器中尝试时,该 URL 有效
-
@HiradRoshandel 除非您要部署浏览器,否则您需要测试您的 NodeJS 代码。您在这里所拥有的应该工作。
标签: javascript json node.js httprequest