26

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!

enrico_alvarenga
  • 371
  • 1
  • 3
  • 5

5 Answers5

27

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
14

you can use Axios client as Axios is a Promise based HTTP client for the browser as well as node.js.

Using Promises is a great advantage when dealing with code that requires a more complicated chain of events. Writing asynchronous code can get confusing, and Promises are one of several solutions to this problem.

First install Axios in your application using npm install axios --save

and then you can use this code

const axios = require('axios');

axios.get('api-url')
    .then(response => {
        console.log(response.data.status);
        // console.log(response.data);
        res.send(response.data.status);
    })
    .catch(error => {
        console.log(error);
    });
Lotus91
  • 1,127
  • 4
  • 18
  • 31
GUDDU KUMAR
  • 401
  • 4
  • 12
1

Kindly try out this solution. i used it and it worked for me.

var Request = require("request");

Request.get("http://httpbin.org/ip", (error, response, body) => {
    if(error) {
        return console.dir(error);
    }
    console.dir(JSON.parse(body));
});
1

You can use request-promise-native that uses native ES6 promises.

Install the request-promise-native package

npm install --save request
npm install --save request-promise-native

Use it as follows :

const request = require('request-promise-native');

const options = {
    method: 'GET',
    uri: 'https://www.google.com'
}

request(options).then(response => {
    console.log(response);
}, error => {
    console.log(error);
});
Nikhil Londhe
  • 41
  • 2
  • 6
1

2022 update

Built in fetch api is available in NodeJS 18+. Third party npm modules are no longer needed.

(async () => {
    const res = await fetch('https://dummyjson.com/products/1')
    if (res.ok) {
        const data = await res.json()
        console.log(data)
    }
})()

More details in the official blog

Basil K Y
  • 490
  • 5
  • 8