wretch is a small wrapper around fetch designed to simplify the way to perform network requests and handle responses.Fetch needs a second callback to process the response body.
fetch("examples/example.json") .then(response => response.json()) .then(json => { //Do stuff with the parsed json });
Wretch does it for you.
// Use .res for the raw response, .text for raw text, .json for json, .blob for a blob ... wretch("examples/example.json") .get() .json(json => { // Do stuff with the parsed json });
Fetch won’t reject on HTTP error status.
fetch("anything") .then(response => { if(!response.ok) { if(response.status === 404) throw new Error("Not found") else if(response.status === 401) throw new Error("Unauthorized") else if(response.status === 418) throw new Error("I'm a teapot !") else throw new Error("Other error") } else // ... }) .then(data => /* ... */) .catch(error => { /* ... */ })
Wretch throws when the response is not successful and contains helper methods to handle common codes.
wretch("anything") .get() .notFound(error => { /* ... */ }) .unauthorized(error => { /* ... */ }) .error(418, error => { /* ... */ }) .res(response => /* ... */) .catch(error => { /* uncaught errors */ })
With fetch you have to set the header, the method and the body manually.
fetch("endpoint", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ "hello": "world" }) }).then(response => /* ... */) // Omitting the data retrieval and error management parts…
With wretch, you have shorthands at your disposal.
wretch("endpoint") .post({ "hello": "world" }) .res(response => /* ... */)
A Wretch object is immutable which means that you can reuse previous instances safely.
// Cross origin authenticated requests on an external API const externalApi = wretch("http://external.api") // Base url // Authorization header .auth(`Bearer ${token}`) // Cors fetch options .options({ credentials: "include", mode: "cors" }) // Handle 403 errors .resolve((_) => _.forbidden(handle403)); // Fetch a resource const resource = await externalApi // Add a custom header for this request .headers({ "If-Unmodified-Since": "Wed, 21 Oct 2015 07:28:00 GMT" }) .get("/resource/1") .json(handleResource); // Post a resource externalApi .url("/resource") .post({ "Shiny new": "resource object" }) .json(handleNewResourceResult);
npm i wretch # or yarn/pnpm add wretch
The package contains multiple bundles depending on the format and feature set located under the /dist/bundle folder.
💡 If you pick the core bundle, then to plug addons you must import them separately from
/dist/bundle/addons/[addonName].min.js
| Feature set | File Name |
|---|---|
| Core features only | wretch.min.js |
| Core + all addons | wretch.all.min.js |
| Format | Extension |
|---|---|
| ESM | .min.mjs |
| CommonJS | .min.cjs |
| UMD | .min.js |
<!-- Pick your favourite CDN: - https://unpkg.com/wretch - https://cdn.jsdelivr.net/npm/wretch/ - https://www.skypack.dev/view/wretch - https://cdnjs.com/libraries/wretch - … --> <!-- UMD import as window.wretch --> <script src="https://unpkg.com/wretch"></script> <!-- Modern import --> <script type="module"> import wretch from 'https://cdn.skypack.dev/wretch/dist/bundle/wretch.all.min.mjs' // ... // </script>
wretch@^2 is compatible with modern browsers only. For older browsers please use wretch@^1.
Wretch is compatible with and tested in Node.js >= 14. Older versions of node may work but it is not guaranteed.
Starting from Node.js 18, node includes experimental fetch support. Wretch will work without installing any polyfill.
For older versions, the Node.js standard library does not provide a native implementation of fetch (and other Browsers-only APIs) and polyfilling is mandatory.
The non-global way (preferred):
import fetch, { FormData } from "node-fetch" // w is a reusable wretch instance const w = wretch().polyfills({ fetch, FormData, });
Globally:
import fetch, { FormData } from "node-fetch"; // Either mutate the global object… global.fetch = fetch; global.FormData = FormData; // …or use the static wretch.polyfills method to impact every wretch instance created afterwards. wretch.polyfills({ fetch, FormData, });
Works with Deno >= 0.41.0 out of the box.
Types should be imported from /dist/types.d.ts.
// You can import wretch from any CDN that serve ESModules. import wretch from "https://cdn.skypack.dev/wretch"; const text = await wretch("https://httpstat.us").get("/200").text(); console.log(text); // -> 200 OK
// ECMAScript modules import wretch from "wretch" // CommonJS const wretch = require("wretch") // Global variable (script tag) window.wretch
import wretch from "wretch" // Instantiate and configure wretch const api = wretch("https://jsonplaceholder.typicode.com", { mode: "cors" }) .errorType("json") .resolve(r => r.json()) try { // Fetch users const users = await api.get("/users") // Find all posts from a given user const user = users.find(({ name }) => name === "Nicholas Runolfsdottir V") const postsByUser = await api.get(`/posts?userId=${user.id}`) // Create a new post const newPost = await api.url("/posts").post({ title: "New Post", body: "My shiny new post" }) // Patch it await api.url("/posts/" + newPost.id).patch({ title: "Updated Post", body: "Edited body" }) // Fetch it await api.get("/posts/" + newPost.id) } catch (error) { // The API could return an empty object - in which case the status text is logged instead. const message = typeof error.message === "object" && Object.keys(error.message).length > 0 ? JSON.stringify(error.message) : error.response.statusText console.error(`${error.status}: ${message}`) }
A high level overview of the successive steps that can be chained to perform a request and parse the result.
// First, instantiate wretch wretch(baseUrl, baseOptions)
The "request" chain starts here.
// Optional - A set of helper methods to set the default options, set accept header, change the current url… .<helper method(s)>() // Optional - Serialize an object to json or FormData formats and sets the body & header field if needed .<body type>() // Required - Sends the get/put/post/delete/patch request. .<http method>()
The "response" chain starts here.
Fetch is called after the request chain ends and before the response chain starts.<br> The request is on the fly and now it is time to chain catchers and finally call a response type handler.
// Optional - You can chain error handlers here .<catcher(s)>() // Required - Specify the data type you need, which will be parsed and handed to you .<response type>() // >> Ends the response chain.
From this point on, wretch returns a standard Promise.
.then(…) .catch(…)
💡 The API documentation is now autogenerated and hosted separately, click the links access it.
These methods are available from the main default export and can be used to instantiate wretch and configure it globally.
import wretch from "wretch" wretch.options({ mode: "cors" }) let w = wretch("http://domain.com/", { cache: "default" })
Helper Methods are used to configure the request and program actions.
w = w .url("/resource/1") .headers({ "Cache-Control": no-cache }) .content("text/html")
Specify a body type if uploading data. Can also be added through the HTTP Method argument.
w = w.body("<html><body><div/></body></html>")
Sets the HTTP method and sends the request.
Calling an HTTP method ends the request chain and returns a response chain. You can pass optional url and body arguments to these methods.
// These shorthands: wretch().get("/url"); wretch().post({ json: "body" }, "/url"); // Are equivalent to: wretch().url("/url").get(); wretch().json({ json: "body" }).url("/url").post();
NOTE: if the body argument is an Object it is assumed that it is a JSON payload and it will have the same behaviour as calling .json(body) unless the Content-Type header has been set to something else beforehand.
Catchers are optional, but if none are provided an error will still be thrown for http error codes and it will be up to you to catch it.
wretch("...") .get() .badRequest((err) => console.log(err.status)) .unauthorized((err) => console.log(err.status)) .forbidden((err) => console.log(err.status)) .notFound((err) => console.log(err.status)) .timeout((err) => console.log(err.status)) .internalError((err) => console.log(err.status)) .error(418, (err) => console.log(err.status)) .fetchError((err) => console.log(err)) .res();
The error passed to catchers is enhanced with additional properties.
type WretchError = Error & { status: number; response: WretchResponse; text?: string; json?: Object; };
The original request is passed along the error and can be used in order to perform an additional request.
wretch("/resource") .get() .unauthorized(async (error, req) => { // Renew credentials const token = await wretch("/renewtoken").get().text(); storeToken(token); // Replay the original request with new credentials return req.auth(token).get().unauthorized((err) => { throw err; }).json(); }) .json() // The promise chain is preserved as expected // ".then" will be performed on the result of the original request // or the replayed one (if a 401 error was thrown) .then(callback);
Setting the final response body type ends the chain and returns a regular promise.
All these methods accept an optional callback, and will return a Promise resolved with either the return value of the provided callback or the expected type.
// Without a callback wretch("...").get().json().then(json => /* json is the parsed json of the response body */) // Without a callback using await const json = await wretch("...").get().json() // With a callback the value returned is passed to the Promise wretch("...").get().json(json => "Hello world!").then(console.log) // => Hello world!
If an error is caught by catchers, the response type handler will not be called.
Addons are separate pieces of code that you can import and plug into wretch to add new features.
import FormDataAddon from "wretch/addons/formData" import QueryStringAddon from "wretch/addons/queryString" // Add both addons const w = wretch().addon(FormDataAddon).addon(QueryStringAddon) // Additional features are now available w.formData({ hello: "world" }).query({ check: true })
Typescript should also be fully supported and will provide


免费创建高清无水印Sora视频
Vora是一个免费创建高清无水印Sora视频的AI工具


最适合小白的AI自动化工作流平台
无需编码,轻松生成可复用、可变现的AI自动化工作流

大模型驱动的Excel数据处理工具
基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


AI论文写作指导平台
AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全 ,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。


AI一键生成PPT,就用博思AIPPT!
博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。


AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。


企业专属的AI法律顾问
iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。


稳定高效的流量提升解决方案,助力品牌曝光
稳定高效的流量提升解决方案,助力品牌曝光


最新版Sora2模型免费使用,一键生成无水印视频
最新版Sora2模型免费使用,一键生成无水印视频
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号