Using http.request in Node.JS while passing an API key

13,125

Here's an example of code I have used to call web APIs with a key in the header:

  var api = http.createClient(80, 'api.example.org');

  var request = api.request('GET', '/api/foo', 
    {
      'host': 'api.example.org',
      'accept': 'application/json', 
      'api-key': 'apikeygoeshere' 
    });

  request.on('response', function (response) {});    
  request.end();
Share:
13,125
JonLim
Author by

JonLim

Developer, gamer, hobbyist chef, professional food destroyer.

Updated on July 17, 2022

Comments

  • JonLim
    JonLim almost 2 years

    I am currently fiddling around with Node.JS to try to create a package for PostageApp to be able to send emails through our API.

    To start, I am using the following code to test out how Node.JS can best interface with our API, but it doesn't seem to want to pass along the API key that I have attached as part of the headers.

    var http = require('http');
    
    function onRequest(request, response) {
      response.end();
    }
    
    http.createServer(onRequest).listen(8888);
    console.log("Server has started.");
    
    var options = {
        host: 'api.postageapp.com',
        path: '/v.1.0/get_account_info.json',
        method: 'POST',
        headers: { "api_key" : "MY API KEY HERE" }
    };
    
    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });
    
    req.end();
    console.log("Request sent!");
    

    I pulled this together using various examples and what not - it's not pretty, I know. However, using HTTPS, I finally got it to hit our API and get a response:

    {"response":{"status":"unauthorized","message":"Invalid or inactive API key used","uid":null}}
    

    The only conclusion I can come up with is that the API key is not getting passed along, and I would appreciate any help as to how to make that happen.

    Thanks!