-
Notifications
You must be signed in to change notification settings - Fork 0
NodeJS
Gaurav Walia edited this page May 30, 2020
·
3 revisions
- Using https node core module
- Using axios node package
- Using node-fetch package
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);
});
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: ''
}
]
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.
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.