How to make a external API call inside express server?

enrico_alvarenga picture enrico_alvarenga · Oct 24, 2016 · Viewed 50.6k times · Source

Hello I ve been trying to implement OneSignal API on my dashboard and I wonder if it is possible to make a API external call inside express server.

Here is an example:

var sendNotification = function(data) {
  var headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
  };

  var options = {
    host: "onesignal.com",
    port: 443,
    path: "/api/v1/notifications",
    method: "POST",
    headers: headers
  };

  var https = require('https');
  var req = https.request(options, function(res) {  
    res.on('data', function(data) {
      console.log("Response:");
      console.log(JSON.parse(data));
    });
  });

  req.on('error', function(e) {
    console.log("ERROR:");
    console.log(e);
  });

  req.write(JSON.stringify(data));
  req.end();
};

Here it is the app route

app.post('/path', function(req, res){


var message = { 
  app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
  contents: {"en": "English Message"},
  included_segments: ["All"]
};

sendNotification(message);
});

Thank you!

Answer

jfriend00 picture jfriend00 · Oct 24, 2016

I wonder if it is possible to make a API external call inside express server.

Sure, you can contact any external server from a node.js app with http.request() like you are showing or one of the higher level modules built on top of that like the request module.

Here's a simple example from the request module home page:

const request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage. 
  }
});

Or, using promises:

 const rp = require('request-promise');
 rp('http://www.google.com').then(body => {
     console.log(body);
 }).catch(err => {
     console.log(err);
 });

EDIT Jan, 2020 - request() module in maintenance mode

FYI, the request module and its derivatives like request-promise are now in maintenance mode and will not be actively developed to add new features. You can read more about the reasoning here. There is a list of alternatives in this table with some discussion of each one. I have been using got() myself and it's built from the beginning to use promises and is simple to use.