Consume JSON web service from Node/Express request

2020-06-06 02:51发布

问题:

I have the following route:

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

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.

Thanks

回答1:

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

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

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!

EDIT: 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.



回答2:

The first argument you supplied to http.get isn't correct. See the node.js docs regarding this function. Instead of passing in options just pass in the full URL as a string, e.g.

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

EDIT: After your edit, the options argument still isn't correct. If you want to use an options dictionary, specify this:

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