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