How to make a external API call inside express server? How to make a external API call inside express server? express express

How to make a external API call inside express server?


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.


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


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