browser-fetch-json
<img src=https://centerkey.com/graphics/center-key-logo.svg align=right width=200 alt=logo>
A thin wrapper around node-fetch just for JSON
Why would you fetch anything but json? ;)
A) Setup
Install with the command:
$ npm install browser-fetch-json
Then import with the line:
const fetchJson = require('browser-fetch-json');
B) Examples
HTTP GET
Fetch the NASA Astronomy Picture of the Day:
const fetchJson = require('browser-fetch-json');
const url = 'https://api.nasa.gov/planetary/apod';
const params = { api_key: 'DEMO_KEY' };
function handleData(data) {
console.log('The NASA APOD for today is at: ' + data.url);
}
fetchJson.get(url, params).then(handleData);
HTTP POST
Create a resource for the planet Jupiter:
const fetchJson = require('browser-fetch-json');
const resource = { name: 'Jupiter', position: 5 };
function handleData(data) {
console.log(data);
}
fetchJson.post('https://httpbin.org/post', resource)
.then(handleData)
.catch(console.error);
C) Leverages node-fetch
browser-fetch-json depends on and calls node-fetch.
For comparison, the above POST example to create a planet would be done directly using node-fetch with the code:
const fetch = require('node-fetch');
const resource = { name: 'Jupiter', position: 5 };
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(resource)
};
function handleData(data) {
console.log(data);
}
fetch('https://httpbin.org/post', options)
.then(response => response.json())
.then(handleData)
.catch(console.error);
The examples for browser-fetch-json and node-fetch each produce the same output.
D) Details
The browser-fetch-json module automatically:
- Serializes the body payload with
JSON.stringify()
. - Adds the JSON data type (
'application/json'
) to the HTTP headers. - Builds the URL query string from the
params
object for GET requests. - Runs
.json()
on the response from the promise.
E) API
The format for using browser-fetch-json is:
GET
fetchJson.get(url, params, options).then(callback);
POST
fetchJson.post(url, resource, options).then(callback);
PUT
fetchJson.put(url, resource, options).then(callback);
PATCH
fetchJson.patch(url, resource, options).then(callback);
DELETE
fetchJson.delete(url, resource, options).then(callback);
Notes:
- Only the
url
parameter is required. The other parameters are optional. - The
params
object for fetchJson.get()
is converted into a query string and appended to the url
. - The
resource
object is turned into the body of the HTTP request. - The
options
parameter is passed through to node-fetch (see the node-fetch documentation for supported options).
Dynamic HTTP method
If you need to programmatically set the method, use the format:
fetchJson.request(method, url, data, options).then(callback);
Where method
is 'GET'
, 'POST'
, 'PUT'
, 'PATCH'
, or 'DELETE'
, and data
represents
either params
or resource
.
F) Questions or enhancements
Feel free to submit an issue.
MIT License