updated-fetchit v3.0.1
fetchit
fetchit provides additional utilities for fetch that works in both Node and the browser.
Installation
yarn
yarn add fetchitnpm
npm install --save fetchitDocumentation
By default, fetchit works identically to fetch with the exception that it will throw a StatusCodeError for non-200 responses.
In addition to the standard fetch API, fetchit adds a few extra utilities:
fetchit.json
fetchit.json() accepts the same arguments as fetch, but rather than the full response object, it will return a JSON object:
import fetchit from 'fetchit'
console.log('result', await fetchit.json('https://httpbin.org/anything'))fetchit.text
fetchit.text() accepts the same arguments as fetch, but rather than the full response object, it will return the response body as a string:
import fetchit from 'fetchit'
console.log('result', await fetchit.text('https://httpbin.org/robots.txt'))Functional Access
In addition to fetchit.json() and fetchit.text(), you can access them in a functional way as well:
import fetchit, { json, text } from 'fetchit'
console.log('result', await json(fetchit('https://httpbin.org/anything'))
console.log('result', await text(fetchit('https://httpbin.org/robots.txt'))options
fetchit supports additional options beyond what fetch provides by default:
query
You can pass in a query object to be formatted and tacked onto the URL as a query string:
const fetch = require('fetchit')
console.log(
'result',
await fetch.json('https://httpbin.org/get', {
date: Date.now(),
boolean: true,
string: 'string',
}),
)form
You can pass in a form object and fetchit will setup an application/x-www-form-urlencoded request body:
const fetch = require('fetchit')
console.log(
'result',
await fetch.json('https://httpbin.org/form', {
method: 'POST',
form: {
date: Date.now(),
boolean: true,
string: 'string',
},
}),
)body
If you pass an object to body, fetchit will setup a application/json request body:
const fetch = require('fetchit')
console.log(
'result',
await fetch.json('https://httpbin.org/form', {
method: 'POST',
body: {
date: Date.now(),
boolean: true,
string: 'string',
},
}),
)Note: If you pass in a
FormDatainstance as the value ofbodyor you provide aContent-Typeheader, the standardfetchbehavior will apply forbody.
credentials
Unlike fetch, by default, fetchit will set credentials to same-origin.
License
fetchit was created by Shaun Harrison and is made available under the MIT license.
3 years ago