我有以下路线:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
我想调用以下网络服务:http://ergast.com/api/f1/current/last/results并告诉它返回 JSON。
我在索引请求中尝试过类似的操作,但它出错了:
var options = {
host: 'ergast.com',
port: 80,
path:'/api/f1/current/last/results.json'
};
http.get(options, function(response) {
response.setEncoding('utf-8');
console.log("Got response: " + response.statusCode);
var data = JSON.parse(response);
}).on('error', function(e) {
console.log("Got error: " + e.message);
}).on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
我猜我可能在某处漏掉了重点。
谢谢
最佳答案
这应该很简单 :) 我建议您使用请求模块(npm install request,或者将其添加到您的 packages.json 文件中)。
然后您可以执行以下操作:
var request = require("request");
request.get("http://ergast.com/api/f1/current/last/results.json", function (err, res, body) {
if (!err) {
var resultsObj = JSON.parse(body);
//Just an example of how to access properties:
console.log(resultsObj.MRData);
}
});
我看到关于使用 JSONP 而不是直接使用 JSON API 的建议。
JSONP 存在的原因是浏览器上的跨域 API。由于您在服务器上运行它,因此跨域限制不是问题,因此不需要 JSONP。随心所欲,随心所欲!
编辑:我不确定您为什么不尝试这个。如果是错误管理,我现在已经更新了错误管理的代码。
关于javascript - 使用来自 Node/Express 请求的 JSON Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12716439/