Node Express passing request headers in a GET request

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?

The error is some sort of dns error

Error: getaddrinfo ENOTFOUND

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

Note: Error code from the browser is a 503.

I just refactored one stuff here and one there but the snippet seems to be a mix of pure node, express and the lower request API

var http = require("http");
var express = require("express");
var app = express();

app.get("/api/:term", function(req, response) {
  var apiKey = "*****************************************";

  let url = "http://api.football-data.org/v2/competitions/CL/matches";
  var options = {
    method: "GET",
    headers: {
      "X-Auth-Token": apiKey
    }
  };

  let data = "";

  let apiRequest = http.request(url, options, function(res) {
    console.log("Connected");

    res.on("data", chunk => {
      data += chunk;
    });

    res.on("end", () => {
      console.log("data collected");

      response.end(JSON.stringify(data));
    });
  });

  apiRequest.end();
});

http.createServer(app).listen(8080);

Thanks that helped. The data is being collected now but the request just hangs / never ends :disappointed:

Which endpoint are you targeting? I just wrote down the "/api/:term"^^

This is what i see by my side:

I solved it by adding this package: https://www.npmjs.com/package/request-promise
As suggested by someone on stackoverflow. I guess I was not resolving the promise correctly?

  app.get('/api/:league', function(req, res, next) {

      var apiKey = process.env.API_KEY;    
      let url = 'api.football-data.org';
    
      const baseUrl = "http://api.football-data.org/v2/competitions/" + req.params.league + "/standings";

    
      var options = {
        uri: baseUrl,
        method: 'GET',
        json: true,
        headers: {
          'X-Auth-Token': apiKey
        }
      };

      let data = "";
      rp(options)
      .then(function (resp) {

           console.log("data collected");
           res.send(resp);
      
        
      });
  })    

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 :stuck_out_tongue: )

1 Like