mande

mande

轻量级 fetch 封装库 提供智能 API 通信

mande 是一个轻量级的 fetch 封装库,为 API 通信提供智能默认设置。它简化了 HTTP 请求编写,支持 TypeScript,提供 GET、POST 等便捷方法。该库支持授权令牌、全局选项设置,并可用于服务器端渲染环境。mande 旨在帮助开发者高效处理 API 请求,是前端开发中的实用工具。

mandefetchAPI通信JSON处理授权管理Github开源项目

mande ci npm package codecov thanks

Simple, light and extensible wrapper around fetch with smart defaults

Requires fetch support.

mande has better defaults to communicate with APIs using fetch, so instead of writing:

// creating a new user fetch('/api/users', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: 'Dio', password: 'irejectmyhumanityjojo', }), }) .then((response) => { if (response.status >= 200 && response.status < 300) { return response.json() } // reject if the response is not 2xx throw new Error(response.statusText) }) .then((user) => { // ... })

You can write:

const users = mande('/api/users') users .post({ name: 'Dio', password: 'irejectmyhumanityjojo', }) .then((user) => { // ... })

Installation

npm install mande yarn add mande

Usage

Creating a small layer to communicate to your API:

// api/users import { mande } from 'mande' const users = mande('/api/users', usersApiOptions) export function getUserById(id) { return users.get(id) } export function createUser(userData) { return users.post(userData) }

Adding Authorization tokens:

// api/users import { mande } from 'mande' const todos = mande('/api/todos', todosApiOptions) export function setToken(token) { // todos.options will be used for all requests todos.options.headers.Authorization = 'Bearer ' + token } export function clearToken() { delete todos.options.headers.Authorization } export function createTodo(todoData) { return todo.post(todoData) }
// In a different file, setting the token whenever the login status changes. This depends on your frontend code, for instance, some libraries like Firebase provide this kind of callback but you could use a watcher on Vue. onAuthChange((user) => { if (user) setToken(user.token) else clearToken() })

You can also globally add default options to all mande instances:

import { defaults } from 'mande' defaults.headers.Authorization = 'Bearer token'

To delete a header, pass null to the mande instance or the request:

const legacy = mande('/api/v1/data', { headers: { // override all requests 'Content-Type': 'application/xml', }, }) // override only this request legacy.post(new FormData(), { headers: { // overrides Accept: 'application/json' only for this request Accept: null, 'Content-Type': null, }, })

TypeScript

All methods defined on a mande instance accept a type generic to type their return:

const todos = mande('/api/todos', globalOptions) todos .get<{ text: string; id: number; isFinished: boolean }[]>() .then((todos) => { // todos is correctly typed })

SSR (and Nuxt in Universal mode)

To make Mande work on Server, make sure to provide a fetch polyfill and to use full URLs and not absolute URLs starting with /. For example, using node-fetch, you can do:

export const BASE_URL = process.server ? process.env.NODE_ENV !== 'production' ? 'http://localhost:3000' : 'https://example.com' : // on client, do not add the domain, so urls end up like `/api/something` '' const fetchPolyfill = process.server ? require('node-fetch') : fetch const contents = mande(BASE_URL + '/api', {}, fetchPolyfill)

Nuxt 2

Note: If you are doing SSR with authentication, Nuxt 3 hasn't been adapted yet. See #308.

When using with Nuxt and SSR, you must wrap exported functions so they automatically proxy cookies and headers on the server:

import { mande, nuxtWrap } from 'mande' const fetchPolyfill = process.server ? require('node-fetch') : fetch const users = mande(BASE_URL + '/api/users', {}, fetchPolyfill) export const getUserById = nuxtWrap(users, (api, id: string) => api.get(id))

Make sure to add it as a buildModule as well:

// nuxt.config.js module.exports = { buildModules: ['mande/nuxt'], }

This prevents requests from accidentally sharing headers or bearer tokens.

TypeScript

Make sure to include mande/nuxt in your tsconfig.json:

{ "types": ["@types/node", "@nuxt/types", "mande/nuxt"] }

API

Most of the code can be discovered through the autocompletion but the API documentation is available at https://mande.esm.is

Cookbook

Timeout

You can timeout requests by using the native AbortSignal:

mande('/api').get('/users', { signal: AbortSignal.timeout(2000) })

This is supported by all modern browsers.

FormData

When passing Form Data, mande automatically removes the Content-Type header but you can manually set it if needed:

// directly pass it to the mande instance const api = mande('/api/', { headers: { 'Content-Type': null } }) // or when creating the request const formData = new FormData() api.post(formData, { headers: { 'Content-Type': 'multipart/form-data' }, })

Most of the time you should let the browser set it for you.

Related

  • fetchival: part of the code was borrowed from it and the api is very similar
  • axios:

License

MIT

编辑推荐精选

音述AI

音述AI

全球首个AI音乐社区

音述AI是全球首个AI音乐社区,致力让每个人都能用音乐表达自我。音述AI提供零门槛AI创作工具,独创GETI法则帮助用户精准定义音乐风格,AI润色功能支持自动优化作品质感。音述AI支持交流讨论、二次创作与价值变现。针对中文用户的语言习惯与文化背景进行专门优化,支持国风融合、C-pop等本土音乐标签,让技术更好地承载人文表达。

QoderWork

QoderWork

阿里Qoder团队推出的桌面端AI智能体

QoderWork 是阿里推出的本地优先桌面 AI 智能体,适配 macOS14+/Windows10+,以自然语言交互实现文件管理、数据分析、AI 视觉生成、浏览器自动化等办公任务,自主拆解执行复杂工作流,数据本地运行零上传,技能市场可无限扩展,是高效的 Agentic 生产力办公助手。

lynote.ai

lynote.ai

一站式搞定所有学习需求

不再被海量信息淹没,开始真正理解知识。Lynote 可摘要 YouTube 视频、PDF、文章等内容。即时创建笔记,检测 AI 内容并下载资料,将您的学习效率提升 10 倍。

AniShort

AniShort

为AI短剧协作而生

专为AI短剧协作而生的AniShort正式发布,深度重构AI短剧全流程生产模式,整合创意策划、制作执行、实时协作、在线审片、资产复用等全链路功能,独创无限画布、双轨并行工业化工作流与Ani智能体助手,集成多款主流AI大模型,破解素材零散、版本混乱、沟通低效等行业痛点,助力3人团队效率提升800%,打造标准化、可追溯的AI短剧量产体系,是AI短剧团队协同创作、提升制作效率的核心工具。

seedancetwo2.0

seedancetwo2.0

能听懂你表达的视频模型

Seedance two是基于seedance2.0的中国大模型,支持图像、视频、音频、文本四种模态输入,表达方式更丰富,生成也更可控。

nano-banana纳米香蕉中文站

nano-banana纳米香蕉中文站

国内直接访问,限时3折

输入简单文字,生成想要的图片,纳米香蕉中文站基于 Google 模型的 AI 图片生成网站,支持文字生图、图生图。官网价格限时3折活动

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成热门AI工具AI图像AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

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

下拉加载更多