I have been struggling with this for days now.
Has anyone any experience of doing this? The API I am calling uses a custom header as a method of authorization.
(This is the API I was trying out https://www.football-data.org/documentation/api)
It works in Postman but setting headers there is a doddle.
var express = require('express');
var app = express();
var http = require('http');
var router = express.Router();
module.exports = (app) => {
/* GET league tables */
app.get('/api/:term', function(req, res, next) {
var apiKey = process.env.API_KEY;
let url = "http://api.football-data.org/v2/competitions/BL1/standings" ; // + req.params.term + "/standings";
var options = {
host: url,
method: 'GET',
headers: {
'X-Auth-Token': apiKey
}
};
var getReq = http.request(options,function(res){
console.log("Connected");
res.on('data',function(data){
console.log(data);
});
});
getReq.end();
})
app.get('/api', function(req, res, next) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Now add a search term to the end of the URL in the address bar');
})
}
Note, the equivalent jQuery code is just:
$.ajax({
headers: { 'X-Auth-Token': 'YOUR_API_KEY' },
url: 'http://api.football-data.org/v2/competitions/BL1/standings',
dataType: 'json',
type: 'GET',
}).done(function(response) {
// do something with the response, e.g. isolate the id of a linked resource
console.log(response);
});
Does it gives you an error ( 401 or other)? Have you tried to set the header manually from the browser?
If Postman and your node server works ( does it? ) maybe some unwanted character (line feed, quotes, ā¦) in the API?
as if the host parameter is wrong. All the examples I see use localhost but Iām not using localhost - I am using glitch. I assume host is the location I am requesting the data from?
I tried just using get but same issue:
var getReq = http.get(options,function(err, res){
if (err) console.log(err);
console.log("Connected");
res.on('data',function(data){
console.log(data);
});
});
There was not promise up there ( at least none i can see ^^ );
If the request was hanging was due to the missing ( or unreachability ) of response.end i guess ^^
Anyway using a request library make things much cleaner ( aswell the use of express send method )