Skip to content
Gaurav Walia edited this page May 30, 2020 · 3 revisions

For hitting APIs using Nodejs there are three methods for hitting APIs with nodejs

  1. Using https node core module
  2. Using axios node package
  3. Using node-fetch package

1. Using https node core module

This tutorial will show you how you can call our APIs using https core module of nodejs.

Create a filename hello.js can copy the code below:

const https = require('https');

https.get('https://treasurejsapi.herokuapp.com/api/v1/search?find=as', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data));
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});

OUTPUT

For output run the code from the terminal node hello.js and you will get the below output

[ 
   { 
       description: 'Official React bindings for Redux',
       docs: 'http://caolan.github.io/async/docs.html',
       github: 'https://github.com/caolan/async',
       name: 'ASYNC',
       other: [],
       website: 'http://caolan.github.io/async/' 
   },
   { 
       description: 'astroturf lets you write CSS in your JavaScript files without adding any runtime layer, and with your existing CSS processing pipeline.',
       docs: '',
       github: 'https://github.com/4Catalyzer/astroturf',
       name: 'ASTROTURF',
       other: [],
       website: '' 
   } 
]

2. Using axios node package

For using axios with nodejs follow the steps:

  1. create a empty folder name test
  2. Go in that folder and open terminal/cmd
  3. Execute command npm init
  4. Then you will have package.json file in your folder
  5. Create a new file index.js in test folder
  6. Now we will install axios nodejs package using
yarn add axios
#or
npm install axios
  1. After installing now copy the given code below in index.js file
const axios = require('axios');

axios.get('https://treasurejsapi.herokuapp.com/api/v1/search?find=as')
.then(res =>{
    console.log(res.data);
})
.catch(err => console.log(err))
  1. Then for seeing the output run command node index.js.

For more details about this package see axios.

3. Using node-fetch package

For hitting GET API request with node-fetch follow the above 5 steps then follow the below steps:

  1. Now we will install node-fetch package using
yarn add node-fetch
#or
npm install node-fetch
  1. After installing now copy the given code below in index.js file
const fetch = require('node-fetch');

fetch('https://treasurejsapi.herokuapp.com/api/v1/search?find=as')
.then(res => console.log(res.data))
.catch(err => console.log(err))
  1. Then for seeing the output run command node index.js.

For more details about this package see node-fetch.