fetch-json-simple v0.1.3
fetch-json-simple
Configurable wrapper around fetch to retrieve JSON
Main features:
- Attaches relevant headers for JSON:
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } - Stringifies request
{ body }(but can also handle already stringified body) - Text responses converted to JSON
{ body } - Options are merged rather than assigned.
- Auto-specifies
{method: 'post'}if omitted and a body was passed - Shortcut methods:
fetch.get,fetch.post,fetch.put, ...
Additional features:
- Configurable
fetch- use either native or polyfill - Configurable
host- prefixed to paths before sending request - ... see #config
Other similar libraries: json-fetch, fetch-json.
Install
npm install fetch-json-simple --saveUsage
Example
fetch('/data-path')
.then(json => {
if (json.body) {
// text body
} else {
// json
}
}).catch(error => {
})API
fetch(path, options)path[string](required)Path to make request to.options[object]Options object containing headers, body etc.bodycan be plain JS object.Merged with configured options object (see #config) and the following json-related default options object:
defaults = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, }merge({}, defaults, // above {method: body ? 'post' : 'get'}, fetch.options, // configured opts, // passed as argument {body} // after stringifying )
Shortcut Methods
fetch.⟪method⟫(...)getEquivalent of:fetch(path, {method: 'get'})postEquivalent of:fetch(path, {method: 'post'})- ...
put,patch,delete〃
Config
fetch.⟪config⟫ = ...host[string](default:none)Use this host to add all paths to before making the fetch requestfetch.host = 'http://server.com'options[object](default:none)Default set of options used in every fetch request. Merged with actual (json-related) options.fetch.options = { headers: { 'Cache-Control': 'no-cache' // 'Accept': 'application/json', < will still be present in final request 'Content-Type': 'json' // < overridden default json-related option } }fetch[function](default:none(uses native))Underlyingfetchfunction to use. Use this to polyfill if needed.fetch.fetch = require('isomorphic-fetch')You may also use
isomorphic-fetchto globally polyfill the underlying fetch in which case the above won't be needed.