NodeJS - TECHOUS/TreasureApis GitHub Wiki
For hitting APIs using Nodejs there are three methods for hitting APIs with nodejs
- Using https node core module
- Using axios node package
- 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:
- create a empty folder name
test
- Go in that folder and open terminal/cmd
- Execute command
npm init
- Then you will have package.json file in your folder
- Create a new file
index.js
intest
folder - Now we will install
axios
nodejs package using
yarn add axios
#or
npm install axios
- 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))
- 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:
- Now we will install
node-fetch
package using
yarn add node-fetch
#or
npm install node-fetch
- 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))
- Then for seeing the output run command
node index.js
.
For more details about this package see node-fetch.