Utilities for custom fetch.
npm install create-fetch
import 'cross-fetch/polyfill' // add universal-fetch polyfill if needed
import createFetch, {query, headers, bodify} from 'create-fetch'
const myFetch = createFetch(fetch, [
query(),
bodify(),
headers({'x-requested-with': 'fetch'}),
])
// same as:
// const myFetch = compose(query(), ...)(fetch)
// could also use pipeline operator:
// const myFetch = fetch |> query() |> ...
myFetch('/api', {
method: 'POST',
query: {filter: 'user'},
body: {name: 'JoJo'},
})
// =>
// POST /api?filter=user
// Request Headers:
// content-type: application/json
// x-requested-with: fetch
// Request Payload:
// {"name":"JoJo"}
Import from module
script (1.4K gzip size):
<script type="module">
import createFetch, {query, headers} from 'https://unpkg.com/create-fetch'
const myFetch = createFetch(fetch, [
query(),
headers({'x-requested-with': 'fetch'}),
])
myFetch('/api', {query: {foo: 'bar'}})
</script>
Add default request options.
import {defaults} from 'create-fetch'
const myFetch = defaults({
credentials: 'same-origin',
})(fetch)
myFetch('/')
Add request base url.
import {baseUrl} from 'create-fetch'
const ghApi = baseUrl('https://api.github.com')(fetch)
ghApi('/users')
// =>
// GET https://api.github.com/users
Add default request headers.
import {headers} from 'create-fetch'
const myFetch = headers({
'x-requested-with': 'fetch',
})(fetch)
myFetch('/')
// =>
// GET /
// Request Headers:
// x-requested-with: fetch
Stringify query string.
import {query} from 'create-fetch'
const myFetch = query()(fetch)
myFetch('/', {
query: {filter: 'user'},
})
// =>
// GET /?filter=user
Stringify request body.
import {bodify} from 'create-fetch'
const myFetch = bodify()(fetch)
// stringify json by default
myFetch('/', {
method: 'POST',
body: {name: 'JoJo'},
})
// =>
// POST /
// Request Headers:
// content-type: application/json
// Request Payload:
// {"name":"JoJo"}
// stringify form
myFetch('/', {
method: 'POST',
body: new URLSearchParams({name: 'JoJo'}),
})
// =>
// POST /
// Request Headers:
// content-type: application/x-www-form-urlencoded
// Request Payload:
// name=JoJo
Add XSRF token header.
import {xsrf} from 'create-fetch'
const myFetch = xsrf({
cookieName, // defaults to `_xsrf`
headerName, // defaults to `x-xsrftoken`
})(fetch)
myFetch('/', {
method: 'POST',
})
// =>
// POST /
// Request Headers:
// x-xsrftoken: <xsrf-token>