@roadhog/fetch
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

Fetch 请求的简单封装

import { createFetch } from '@roadhog/fetch';

const $fetch = createFetch({
	// 支持字符串或者对象
	// baseURL: 'https://a.com',可省略 base
	baseURL: {
		a: 'https://a.com',
		b: 'https://b.com'
	},
	// baseURL 为字符串;base 可忽略
	// baseURL 为对象;base 可以设置为 baseURL 的 key,不行默认使用第一个key,即:a
	base: 'b',
	// 每个请求会触发
	onRequest: (ctx: FetchContext) => {
		// 设置请求头等
		ctx.options.headers = { token: 'token' };
	},
	onError: (ctx: FetchContext) => {
		// 请求错误
		// message 为每个请求配置的 errorStatusCodes 对应的状态码
		// errorStatusCodes 没有配置则显示默认的http 状态码对应的statusText
		ctx.error?.message;
		ctx.response;
	}
});

get 请求

$fetch.get('/users', { params: { page: 1, max: 10 } });

post put patch delete 请求

  • 也支持 params 参数
// 请求头为 Content-Type: application/x-www-form-urlencoded
// 使用 data
const data = { name: 'fetch' };
$fetch.post('/users', { data });

// 请求头为 Content-Type: application/json
// 使用 data
const body = { name: 'fetch' };
$fetch.post('/users', { body });

// 可以配置http状态码对应的提示
$fetch.post('/users', { errorStatusCodes: { 404: '找不到' } });

Readme

Keywords

Package Sidebar

Install

npm i @roadhog/fetch

Weekly Downloads

0

Version

1.0.2

License

none

Unpacked Size

12.2 kB

Total Files

8

Last publish

Collaborators

  • roadhog