Skip to content

shnhrrsn/fetchit

Repository files navigation

Build Status Total Downloads Latest Version License

fetchit

fetchit provides additional utilities for fetch that works in both Node and the browser.

Compatibility

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

Installation

yarn

yarn add fetchit

npm

npm install --save fetchit

Documentation

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 FormData instance as the value of body or you provide a Content-Type header, the standard fetch behavior will apply for body.

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.

About

Extra utilities for `fetch` that works in both Node and the browser.

Resources

License

Stars

Watchers

Forks

Packages

No packages published