node js fetch api example
Example 1: node js fetch
const fetch = require('node-fetch'); //npm install node-fetch
fetch('https://httpbin.org/post', {
method: 'POST',
body: 'a=1'
})
.then(res => res.json())
.then(json => {
// Do something...
})
.catch(err => console.log(err));
Example 2: fetch api with express
const url ='https://example.com';
const headers = {
"Content-Type": "application/json",
"client_id": "1001125",
"client_secret": "876JHG76UKFJYGVHf867rFUTFGHCJ8JHV"
}
const data = {
"name": "Wade Wilson",
"occupation": "Murderer",
"age": "30 (forever)"
}
fetch(url, { method: 'POST', headers: headers, body: data})
.then((res) => {
return res.json()
})
.then((json) => {
// Do something with the returned data.
console.log(json);
});
Example 3: node js fetch data from url
var http = require('http');
var options = {
host: 'google.com',
path: '/'
}
var request = http.request(options, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
console.log(data);
});
});
request.on('error', function (e) {
console.log(e.message);
});
request.end();