How to make an external API call inside the express server?

Hello, I'm trying to implement the OneSignal API on my toolbar, and I'm wondering if it is possible to make an external API call inside the 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 is the application 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); }); 

Thanks!

+11
source share
3 answers

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

Of course, you can contact any external server from the node.js application using the http.request() you show, or with one of the higher level modules built on top of it, for example, with the request module .

Here is 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); }); 
+11
source

You can use the Axios client, since Axios is a Promise-based HTTP client for the browser, as well as node.js.

Using Promises is a big advantage when working with code that requires a more complex chain of events. Writing asynchronous code can be confusing, and Promises is 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); }); 
+2
source

Please try this solution. I used this 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)); }); 
0
source

Source: https://habr.com/ru/post/1258722/


All Articles