A better fetch API. Works on node, browser and workers.
Install:
# npm npm i ohmyfetchyarn
yarn add ohmyfetch
Import:
// Universal (requires global.fetch) import { $fetch } from 'ohmyfetch'// NodeJS / Isomorphic import { $fetch } from 'ohmyfetch/node'
// NodeJS / Isomorphic (CommonJS) const { $fetch } = require('ohmyfetch/node')
$fetchSmartly parses JSON and native values using destr and fallback to text if cannot parse
const { users } = await $fetch('/api/users')
$fetchAutomatically throw errors when
response.okis
falsewith a friendly error message and compact stack (hiding internals).
Parsed error body is available with
error.data. You may also use
FetchErrortype.
await $fetch('http://google.com/404') // FetchError: 404 Not Found (http://google.com/404) // at async main (/project/playground.ts:4:3)
In order to bypass errors as reponse you can use
error.data:
await $fetch(...).catch((error) => error.data)
Response can be type assisted:
const { article } = await $fetch(`/api/article/${id}`) // Auto complete working with article.id
baseURL
By using
baseURLoption,
$fetchprepends it with respecting to trailing/leading slashes and query params for baseURL using ufo:
await $fetch('/config', { baseURL })
By using
paramsoption,
$fetchadds params to URL by preserving params in request itself using ufo:
await $fetch('/movie?lang=en', { params: { id: 123 } })
If you need to access raw response (for headers, etc), can use
$fetch.raw:
const response = await $fetch.raw('/sushi')// response.data // response.headers // ...
ohmyfetchpackage with babel for ES5 support
fetchglobal for supporting legacy browsers like using unfetch
Why export is called
$fetchinstead of
fetch?
Using the same name of
fetchcan be confusing since API is different but still it is a fetch so using closest possible alternative.
Why not having default export?
Default exports are always risky to be mixed with CommonJS exports.
This also guarantees we can introduce more utils without breaking the package and also encourage using
$fetchname.
Why not transpiled?
By keep transpiling libraries we push web backward with legacy code which is unneeded for most of the users.
If you need to support legacy users, can optionally transpile the library in build pipeline.
MIT. Made with 💖