fetchit
provides additional utilities for fetch
that works in both Node and the browser.
fetchit 4 requires Node 18 or later and is no longer compatible with node-fetch.
To use with earlier versions of Node, please use fetchit@^3
yarn add fetchit
npm install --save fetchit
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()
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()
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'))
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'))
fetchit
supports additional options
beyond what fetch
provides by default:
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',
}),
)
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',
},
}),
)
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
FormData
instance as the value ofbody
or you provide aContent-Type
header, the standardfetch
behavior will apply forbody
.
Unlike fetch
, by default, fetchit
will set credentials
to same-origin
.
fetchit
was created by Shaun Harrison and is made available under the MIT license.