🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

rslib-fetch

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rslib-fetch

## 安装

latest
npmnpm
Version
0.0.3-alpha.0
Version published
Weekly downloads
2
-50%
Maintainers
1
Weekly downloads
 
Created
Source

rslib-fetch

安装

pnpm install rslib-fetch

使用方式

import { initFetch } from 'rslib-fetch';

// 创建createFetch函数,参数为axios的配置,具体请参考axios。其中errTipFn为错误提示语的调用函数
// 在响应内容为报错的情况下库会调用errTipFn方法,参数为报错内容字符串,
// 可以根据ui框架定义不同的风格
const createFetch = initFetch({
  baseURL: '/baseUrl',
  errTipFn: Message.error,
  timeout: 60 * 1000,
  modifyAxiosInstance: (instance, config) => {},
  ignoreUrlErrTipArr: [],
  responseTypeConfig: {
    successCodeArr: [], // 默认成功状态码
    codeField: 'code', // 默认状态码字段名
    dataField: 'data', // 默认数据字段名
    messageField: 'message', // 默认消息字段名
  },
});

const fetch = createFetch([]);

export default fetch;

配置选项

initFetch 函数接受一个配置对象,该对象包含以下属性:

基础 Axios 配置

这些配置选项直接传递给 Axios 实例。有关所有可用选项,请参阅 Axios 文档

参数类型默认值说明
baseURLstring-请求的基础 URL
timeoutnumber60 * 1000请求超时时间(毫秒)
其他 Axios 配置--任何 Axios 支持的配置项

错误处理配置

参数类型默认值说明
errTipFnFunction-全局错误提示函数,当请求失败(HTTP错误或业务错误)时调用,参数为错误消息字符串
ignoreUrlErrTipArrstring[][]忽略错误提示的 URL 数组(支持字符串匹配,只要请求 URL 包含该字符串即忽略)

响应结构配置

responseTypeConfig 对象用于定义后端返回的数据结构:

参数类型默认值说明
successCodeArrnumber[][]表示成功的业务状态码数组,(如果为空,则根据response的status判断)
codeFieldstring'code'状态码字段名
dataFieldstring'data'数据字段名
messageFieldstring'message'消息字段名

自定义 Axios 实例

参数类型默认值说明
modifyAxiosInstance(instance: AxiosInstance, config: IOptions) => void-用于修改 Axios 实例的函数,接收两个参数:
1. instance: 创建的 Axios 实例
2. config: 传入的配置对象

中间件系统

createFetch 函数接受一个中间件数组。每个中间件是一个函数,具有以下签名:

export type IMiddlewareFn = (
  config: IConfig,
  fetch: IMiddlewareFn,
) => Promise<AxiosResponse>;

中间件示例

const authMiddleware = (config, enhanceFetch) => {
  // 修改请求配置(例如添加认证头)
  config.headers = {
    ...config.headers,
    Authorization: `Bearer ${token}`,
  };
  return enhanceFetch(config, enhanceFetch);
};
const loggingMiddleware = (config, enhanceFetch) => {
  console.log('发送请求:', config.url);
  const start = Date.now();
  return enhanceFetch(config, enhanceFetch)
    .then((response) => {
      console.log(`请求 ${config.url} 完成,耗时 ${Date.now() - start}ms`);
      return response;
    })
    .catch((error) => {
      console.error(`请求 ${config.url} 失败`, error);
      throw error;
    });
};

请求配置(IConfig)

当调用 fetch(config) 时,可以传入以下配置(除了 Axios 的配置外,还有以下扩展):

参数类型默认值说明
paramsRecord<string, any>{}参数
independentbooleanfalse是否全局忽略错误提示(不调用errTipFn方法)
其他 Axios 请求配置--任何 Axios 请求支持的配置项

示例配置

import { initFetch } from 'rslib-fetch';
import { message } from 'antd';
const createFetch = initFetch({
  baseURL: '/api',
  timeout: 60000,
  errTipFn: message.error,
  ignoreUrlErrTipArr: ['/log'],
  responseTypeConfig: {
    successCodeArr: [0, 200],
    codeField: 'code',
    dataField: 'data',
    messageField: 'message',
  },
  modifyAxiosInstance: (axiosInstance) => {
    axiosInstance.defaults.headers.common['X-Requested-With'] =
      'XMLHttpRequest';
  },
});
const fetch = createFetch([
  // 中间件
  (config, enhanceFetch) => {
    // 添加认证头
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    };
    return enhanceFetch(config, enhanceFetch);
  },
]);
export default fetch;

注意事项

  • 错误提示函数 errTipFn 只接收一个字符串参数,即错误消息。
  • 通过 ignoreUrlErrTipArr 可以忽略特定 URL 的错误提示,例如忽略日志接口的错误提示。
  • 使用 modifyAxiosInstance 可以修改 Axios 实例,例如添加拦截器或设置默认头。
  • 中间件的执行顺序与数组中的顺序一致,每个中间件必须调用 enhanceFetch(config, enhanceFetch) 以继续传递请求配置。

FAQs

Package last updated on 01 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts