从Node / Express请求中获取JSON Web服务?

时间:2012-10-03 20:33:06

标签: javascript http node.js express

我有以下路线:

exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};

我想调用以下Web服务: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);
  });

我猜我可能在某处错过了这一点。

由于

2 个答案:

答案 0 :(得分:6)

这应该很简单:)我建议你使用请求模块(npm安装请求,或者只是将它添加到你的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。无论如何,继续前进吧!

编辑:我不确定你为什么不试试这个。如果是用于错误管理,我现在已经使用错误管理更新了代码。

答案 1 :(得分:1)

您提供给http.get的第一个参数不正确。有关此功能,请参阅node.js docs。而不是传入options只需将完整的URL作为字符串传递,例如

http.get('http://ergast.com/api/f1/current/last/results', function(res) {
...

编辑:编辑后,options参数仍然不正确。如果要使用选项字典,请指定:

{ host: 'ergast.com', port: 80, path: '/api/f1/current/last/results' }