antdPro创建的项目网络请求统一处理

项目中经常会对请求进行统一的封装处理,方便我们搭载token、对请求进行拦截等需求。

在React中经常会使用到umi提供的request请求。那么在antdPro创建的项目中,怎么对request请求进行统一的封装呢?实现的话大致有两种方式:

方式一:

是对umi的request进行简单封装,再暴露出去;在项目后续的网络请求统一都使用这个封装后并暴露出去的request方法,具体的处理方式可以参见这篇说明 :umi-request请求封装

方式二:

方式二是最近看umi文档时候发现的,可以直接在antdPro项目的app.tsx文件中对request进行运行时配置,并且该配置会直接透传到umi-request的全局配置。后续直接从umi中引入request或者useRequest直接使用,可以说是非常方便。文档可查看:umi.js

具体配置代码:

import type { RequestConfig } from 'umi';



/** 请求拦截 */
const requestInterceptor = (url: any, options: any): any => {
  const headers = {
    ...options.headers,
    token: localStorage.getItem('token') || '1213'
  }
  return {
    url: url,
    options: { ...options, headers: headers },
  }
};
/** 响应拦截 */
const responseInterceptors = (response: any, options: any): any => {
  debugger
  if (response.status !== 200) {
    switch (response.status) {
      case 401:
        notification.warn({
          message: '登录超时,请重新登陆!',
        });
        history.push('/login');
        break;
    }
  }
  return response;
}
/** 异常处理程序 */
const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队(异步任务)。',
  204: '删除数据成功。',
  400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限(令牌、用户名、密码错误)。',
  403: '用户得到授权,但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除,且不会再得到的。',
  422: '当创建一个对象时,发生一个验证错误。',
  500: '服务器发生错误,请检查服务器。',
  502: '网关错误。',
  503: '服务不可用,服务器暂时过载或维护。',
  504: '网关超时。',
};
const errorHandler = (error: any) => {
  const { response } = error;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    });
  } else if (!response) {
    notification.error({
      description: '您的网络发生异常,无法连接服务器',
      message: '网络异常',
    });
  }
  return response;
};

// request运行时配置
export const request: RequestConfig = {
  timeout: 3000, //请求超时时间
  // prefix: process.env.NODE_ENV === "production" ? config.baseurl :'api/', // 统一的请求前缀

  // 自定义端口规范(可以对后端返回的数据格式按照我们的需求进行处理)
  errorConfig: {
    adaptor: resData => {
      debugger
      return {
        ...resData
      };
    },
  },
  middlewares: [],
  errorHandler: (error) => { errorHandler(error) },    //请求错误处理
  requestInterceptors: [requestInterceptor],           //请求拦截
  responseInterceptors: [responseInterceptors],        //响应拦截
};
//后续使用直接从umi中引入request 或者 useRequest,配置即生效

import { request } from 'umi';

export function login(body: API.LoginParams, options?: Record<string, any>) {
  return request<API.LoginResult>('/devServer/users/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: body,
    ...(options || {}),
  });
}

猜你喜欢

转载自blog.csdn.net/fsfsdgsdg/article/details/125248112