Skip to content
Related Articles

Related Articles

Improve Article

How to call an API continuously from server side itself in NodeJS/ExpressJS ?

  • Last Updated : 19 May, 2021

Calling an API endpoint is the core functionality of modern internet technology. Usually, we call API from the browser. Sometimes we need to call API endpoint from the server itself to fetch data, load dependencies, etc.

There are many ways to call API from NodeJS server itself, depending on the abstraction level that you want to use. The simplest way to call an API from NodeJS server is using the Axios library. 

Project Setup: Create a NodeJS project and initialize it using the following command.

mkdir Project && cd Project
npm init -y

Module Installation: Install the required modules i.e. ExpressJS and Axios using the following command.

npm i express axios

Now create a JS file in the root folder of your project and name it index.js



1. Make an HTTP GET request: Write the following code on your index.js file.

index.js




const express = require('express')
const axios = require('axios')
  
const app = express()
  
// Post ID tracker
var num = 0
  
setInterval(() => {
  
   // Increment post tracker
   num++
   console.log('Wait for 2 second...')
  
   // Make GET Request on every 2 second
   axios.get(
`https://jsonplaceholder.typicode.com/posts/${num}`)
  
      // Print data
      .then(response => {
         const { id, title } = response.data
         console.log(`Post ${id}: ${title}\n`)
      })
  
      // Print error message if occur
      .catch(error => console.log(
            'Error to fetch data\n'))
}, 2000)

Explanation: In the above example, NodeJS call an API in 2-second intervals to fetch data. If the promise is resolved, then the block will be executed and print data. If a promise rejects, catch block will be executed and print an Error message.  

Run the server using the following command:

node index.js 

Output:

2. Make an HTTP POST request: Write down the following code in the index.js file.

index.js




const express = require('express')
const axios = require('axios')
  
const app = express()
  
// Dummy database
const posts = [
   {
      title: 'Headline 1',
      id: 1,
      body: `sint suscipit perspiciatis velit dolorum 
            rerum ipsa laboriosam odio`,
      userId: 1
   },
  
   {
      title: 'Headline 2',
      id: 2,
      body: "fugit voluptas sed molestias voluptatem provident",
      userId: 1
   },
  
   {
      title: 'Headline 3',
      id: 3,
      body: "voluptate et itaque vero tempora molestiae",
      userId: 1
   }
]
  
// Loop over the posts
posts.forEach(post => {
  
   // Post data to API endpoint
      body: post,
   })
  
      // Print response
      .then(response => {
         const { id, title } = response.data.body
         console.log(`Post ${id}: ${title}`)
      })
  
      // Print error message if occur
      .catch(error => console.log(error))
})

Explanation: In the above example, we have created dummy user data. NodeJS makes a POST request to send these data to the API endpoint and print either the response’s data or the error message.

Run the server using the following command:

node index.js 

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :