zoukankan      html  css  js  c++  java
  • umi-request Ant Pro 的请求库

    umi-request

    umi-request 是基于 fetch 的封装,兼具 fetch 和 axios 的特点。旨在为开发者提供便捷统一的请求方式。Ant Pro 中对 其进行了初步的封装。比如:统一的错误处理方式。

    但是,在实际中我们可能会遇见各种各样的情况,需要按照自己的需求对其进行封装。那就首先从 Ant Pro 的统一的异常处理程序开始吧。
    首先,引入umi-request的扩展到项目中。

    import { extend } from 'umi-request';
    

    其次,根据自己的项目实际情况定义错误码和其对应的提示语。

    const codeMessage = {
      200: '服务器成功返回请求的数据。',
      201: '新建或修改数据成功。',
      202: '一个请求已经进入后台排队(异步任务)。',
      204: '删除数据成功。',
      400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
      401: '用户没有权限(令牌、用户名、密码错误)。',
      403: '用户得到授权,但是访问是被禁止的。',
      404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
      406: '请求的格式不可得。',
      410: '请求的资源被永久删除,且不会再得到的。',
      422: '当创建一个对象时,发生一个验证错误。',
      500: '服务器发生错误,请检查服务器。',
      502: '网关错误。',
      503: '服务不可用,服务器暂时过载或维护。',
      504: '网关超时。',
    };
    

    然后,写异常处理函数

    /**
     * 异常处理程序
     */
    const errorHandler = (error: { response: Response }): Response => {
      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请求时的默认参数
     */
    const request = extend({
      errorHandler, // 默认错误处理
      credentials: 'include', // 默认请求是否带上cookie
      // timeout: 60000, // 请求超时
    });
    
    

    首先第一个需求:对请求结果异常的统一处理。比如:token 失效时,应该统一弹框提示,并且跳回到登录页。非成功的统一提示。直接拿到后端返回的数据而去掉外层的包装。

    request.interceptors.response.use(async (response) => {
      const data = await response.clone().json();
      // const currentInterface = getPureInterface(response.url); // 这个方法是为了得到纯接口,然后可以适时的选择跳过,或者做别的操作
      // token 失效
      if(data.code === 1014) {
        window.location.href = `${window.location.origin}/user/login`;
      }
      // 统一报错信息。需特殊跳过的接口可以在这里跳过
      if(data.code === 1009) {
        // ant 引入的组件
        notification.error({
          message: '请求错误',
          description: data.message,
        })
      }
      return response;
    })
    

    比如后端接口不同类型需要的参数格式不同。

    // get 请求,参数拼接在 url 后面。并且需要在 headers 里面添加参数 token
    const requestGet = (url: string, data?: object) => {
      return request.get(`${url}?${qs.stringify({ ...data, t: Date.now() })}`, {
        headers: {
          tokenId: getCookie("token"),
        }
      })
    }
    
    // post 请求,form 格式,每个请求都需要包含 token,accout 参数
    const requestPost = (url: string, data?: object) => {
      return request.post(url, {
        method: 'POST',
        data: {
          ...data,
          tokenId: getCookie("token"),
          account: getCookie("account"),
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          tokenId: getCookie("token"),
        }
      })
    }
    
    // post 请求,要求的入参却是 json 格式
    const requestPostJson = (url: string, data?: object) => {
      return request.post(url, {
        method: 'POST',
        data,
        headers: {
          'Content-Type': 'application/json',
          tokenId: getCookie("token"),
        },
      })
    }
    // 这是全局的拦截,还可以写局部的拦截器
    

    封装完成之后,最后暴露出来即可使用

    export default {
      get: requestGet,
      post: requestPost,
      json: requestPostJson
    };
    

    比如请求前的拦截

    /**
     * 请求前拦截。比如添加数据或者,修改url
     */
    request.interceptors.request.use( (url, options) => {
      // console.log('url=',url)
      // console.log('options', options)
      /**
       * 这里的添加会在上面各自的请求之后执行,比如url 的拼接
       * 这里可以根据 options 的参数决定要不要修改或者拼接不同的前后缀
       * options 包含 credentials、errorHandler、headers、method、params、
       */
      return {
        url: `xingquan${url}&author=guozheng`,
        options: {...options, interceptors: true}
      }
    })
    

    还有好多方便的用法,文档很详细,使用到再补充。

  • 相关阅读:
    C# 进程 与 线程
    Micro 设计文档
    asp.net core 3.0 身份认证 替换为自已的提供程序 AuthenticationStateProvider replace to SelfAuthenticationStateProvider
    https://github.com/commonsensesoftware/More
    .net core中使用Automapper
    使用EntityFramework Core和Enums作为字符串的ASP.NET Core Razor页面——第三部分
    ABP邮件发送
    .net Core中实现SHA加密
    .net c# 文件分片/断点续传之下载--客户端
    .net core 下监控Sql的执行语句
  • 原文地址:https://www.cnblogs.com/xguoz/p/13567048.html
Copyright © 2011-2022 走看看