Package Exports
- fetch-json
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (fetch-json) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
fetch-json

A wrapper around Fetch just for JSON
Why would you fetch anything but json? ;)
1) Setup
Browser
In a web page:
<script src=fetch-json.min.js></script>or from the jsdelivr.com CDN:
<script src=https://cdn.jsdelivr.net/npm/fetch-json@2.1/fetch-json.min.js></script>node
As a module:
$ npm install fetch-jsonthen import with the line:
const fetchJson = require('fetch-json');2) Examples
HTTP GET
Fetch the NASA Astronomy Picture of the Day:
// NASA APoD
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:
// Create Jupiter
const resource = { name: 'Jupiter', position: 5 };
function handleData(data) {
console.log(data); //http response body as an object literal
}
fetchJson.post('https://httpbin.org/post', resource)
.then(handleData)
.catch(console.error);For more examples, see code for Mocha specification cases at: spec-node.js (output)
3) Leverages the Fetch API and node-fetch
fetch-json calls the native Fetch API if in a browser and calls node-fetch if running on node.
For comparison, the above POST example to create a planet would be done calling the Fetch API directly with the code:
// Create Jupiter (with Fetch API instead of fetch-json)
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); //http response body as an object literal
}
fetch('https://httpbin.org/post', options)
.then(response => response.json())
.then(handleData)
.catch(console.error);The examples for fetch-json and the Fetch API each produce the same output.
4) Details
The 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
paramsobject for GET requests. - Runs
.json()on the response from the promise. - Sets
credentialsto'same-origin'to support user sessions for frameworks/servers such as Grails, Rails, PHP, Flask, etc. - If the response body is HTML or text, it's converted to JSON (makes it easier to handle HTTP error status codes).
5) API
The format for using 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
urlparameter is required. The other parameters are optional. - The
paramsobject forfetchJson.get()is converted into a query string and appended to theurl. - The
resourceobject is turned into the body of the HTTP request. - The
optionsparameter is passed through to the Fetch API (see theinitdocumentation on MDN).
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.
Logging
Enable basic logging to the console with:
fetchJson.enableLogger();Pass in a function to use a custom logger or pass in false to disable logging.
The default console output looks like:
2018-09-12T07:20:12.372Z – "GET" – "https://api.nasa.gov/planetary/apod"
Text to JSON
If the HTTP response body is not JSON (Content-Type is not "application/json" or "text/javascript"), an object containing the body as a string in the bodyText field is created and passed on through the promise. In addition to the bodyText field, the object
will have the fields: ok, status, statusText, and contentType.
For example, an HTTP response for an error status of 500 would be converted to an object similar to:
{
ok: false,
status: 500,
statusText: 'INTERNAL SERVER ERROR',
contentType: 'text/html; charset=utf-8',
bodyText: '<!doctype html><html><body>Server Error</body></html>'
}6) Legacy web browsers
To support really old browsers, include polyfills for Promise and Fetch API:
<script src=https://cdn.jsdelivr.net/npm/promise-polyfill@8.1/dist/polyfill.min.js></script>
<script src=https://cdn.jsdelivr.net/npm/whatwg-fetch@3.0/dist/fetch.umd.min.js></script>7) Questions or enhancements
Feel free to submit an issue.