从Node / Express请求消费JSON Web服务? [英] Consume JSON web service from Node/Express request?

查看:99
本文介绍了从Node / Express请求消费JSON Web服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下路线:

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

我想打电话给以下Web服务: http://ergast.com/api/f1/current/last/results 并告诉它返回JSON。

I would like to call the following web service: http://ergast.com/api/f1/current/last/results and tell it to return JSON.

我在索引请求中尝试过这样的东西,但是错误:

I have tried something like this in the index request but it errors:

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);
  });

我猜想我可能在某处失踪了点。

I'm guessing I'm probably missing the point somewhere.

谢谢

推荐答案

这应该是简单的:)我建议你使用请求模块(npm安装请求,或者只是将其添加到您的packages.json文件中)

This should be simple :) I recommend you using the request module (npm install request, or just add it to your packages.json file).

然后,您可以执行以下操作:

Then you can do the following:

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的建议。

I see the suggestion about using JSONP instead of just going straight for the JSON API.

JSONP的原因是浏览器上的跨域API。由于您在服务器上运行此操作,跨域限制不是问题,因此不需要JSONP。继续,按照你的意愿做任何事情!

JSONP's reason for existing is for cross-domain APIs on the browser. Since you're running this on the server, the cross-domain restrictions are not an issue and thus JSONP is not required. Go ahead and do as you wish anyway!

编辑:我不知道为什么你不尝试这个。如果是错误管理,我现在更新了错误管理代码。

I ain't sure about why you don't try this. If it is for error management, I have updated the code with error management now.

这篇关于从Node / Express请求消费JSON Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆