fetch-me-json
High level API for fetch with sensible defaults making client server requests a breeze.
Installation
npm i fetch-me-json
Usage
Convention
import JSONFetch from 'fetch-me-json'
JSONFetch.<<method>>(<<endpoint>>, <<JSON-payload>>)
.then(<<JSON-ResponseBody>> => ...)
.catch(<<errorMessage>> => ...)
GET requests
JSONFetch
You can also pass query parameters.
JSONFetch
POST, PUT, PATCH, DELETE
JSONFetch JSONFetch JSONFetch JSONFetch
Advanced
internal fetch
These are the internal fetch options that will be applied. You can configure these to your liking (see below).
mode: 'same-origin' credentials: 'same-origin' headers: Accept: 'application/json' 'Content-Type': 'application/json'
Configurations
const configurations = errorKey: 'error' JSONFetch
List of possible configurations
key | description | default |
---|---|---|
errorKey | The key (from the response) that should be thrown in the case of an error. Pass null to throw entire response | message |
defaultPayload | define default payload you always want to pass along | |
fetch | parameters to be passed down to the global fetch method, overrides default parameters | see internal fetch above |
baseURL | URL to be prepended for every request's endpoint. E.g. /api or http://localhost:3000 |
Differences to native fetch
- uses and accepts JSON by default
- throws an error when response is not ok
If you need to support older browsers be sure to include the polyfill.
Catching the response status code
JSONFetch returns a custom HttpError
object with a status
property that you can make use of.
JSONFetch