Using javascript fetch in nodejs
Views: 484
Vanilla javascript's native fetch method has a simpler API to make Ajax calls. This post shows how to use it in NodeJS environment.
node-fetch module ( https://www.npmjs.com/package/node-fetch ) brings window.fetch
feature to NodeJS environment.
You can install it by running the following command
npm i node-fetch
Once you added the library you can start making Ajax calls. Following code shows you how to make GET and POST calls using the node-fetch
// Example GET call
const fetch = require('node-fetch');
fetch(<url>)
.then(res => res.json())
.then(json => console.log(json));
// Example POST call
const fetch = require('node-fetch');
let data = { foo: 'bar', i : 10};
fetch( <url>, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(json => console.log(json));
On By
ffc