A very thin wrapper around node-fetch just for JSON
Why would you fetch anything but json? ;)
Install with the command:
$ npm install node-fetch-json --save
Then import with the line:
const fetchJson = require('node-fetch-json');
node-fetch-json depends on and calls node-fetch.
node-fetch enables you to send and receive JSON at a REST endpoint using:
const fetch = require('node-fetch');
const data = { animal: 'dog', action: 'fetch' };
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(data)
};
function handleJson(data) {
console.log(data.origin, data.json);
}
fetch('https://httpbin.org/post', options)
.then(response => response.json())
.then(handleJson)
.catch(console.log);
With node-fetch-json, the above becomes:
const fetchJson = require('node-fetch-json');
const data = { animal: 'dog', action: 'fetch' };
function handleJson(data) {
console.log(data.origin, data.json);
}
fetchJson('https://httpbin.org/post', { method: 'POST', body: data })
.then(handleJson)
.catch(console.log);
Both examples produce output that looks like:
203.0.113.254 { action: 'fetch', animal: 'dog' }
The node-fetch-json module:
- Automatically adds the JSON data type (
'application/json'
) to the HTTP headers. - Automatically serializes the body payload with
JSON.stringify()
. - Automatically runs
.json()
on the response promise.
The format for using node-fetch-json is:
fetchJson(url[, options])
The url
and options
parameters are passed through to node-fetch.
See the documentation for the node-fetch project.
Feel free to submit an issue.