基于 wx.request 封装类似axios的拦截器

该博客介绍了如何在微信小程序的开发过程中,由于wx.request不支持axios样式的请求和响应拦截,作者选择自定义一个HttpClient类来实现这一功能。通过定义请求方式、请求入参类以及请求和响应拦截器,作者创建了一个完整的HTTP客户端,包括GET、HEAD、POST等请求方法,并提供了使用示例。同时,还展示了如何设置请求拦截器(如添加授权头)和响应拦截器(如处理不同状态码的响应)。
摘要由CSDN通过智能技术生成

在开发微信小程序的过程中,因为在接口发送请求需要对请求入参进行统一加密,但是wx.request没有提供类型axios的请求拦截和响应拦截方式,所以觉得自己封装一个。

// 请求方式
export enum HttpMethod {
  GET = "GET",
  HEAD = "HEAD",
  POST = "POST",
  PUT = "PUT",
  DELETE = "DELETE",
  OPTIONS = "OPTIONS",
  TRACE = "TRACE",
  CONNECT = "CONNECT"
}

/// 请求入参
class RequestMessage {
  Api:string;
  Param: any;
  Method: HttpMethod;
  Header: Object;
  constructor(api:string,param:any,method:HttpMethod = HttpMethod.GET,header:any = null){
    this.Api = api;
    this.Param = param;
    this.Method = method;
    this.Header = header;
  }
}

/**
 * HttpClient 实例
 */
class HttpClient {
  private RequestInterceptor: Function | undefined;
  private ReponseInterceptor: Function | undefined;
  private baseUrl: string;
  constructor(baseUrl:string = ''){
    this.baseUrl = baseUrl;
  }
  
  /** 请求拦截器 */
  public UseRequestInterceptor(interceptor:(requestMessage: RequestMessage) => boolean): HttpClient {
    this.RequestInterceptor = interceptor;
    return this;
  }

  /** 响应拦截器 */
  public UseReponseInterceptor(interceptor:(reponseMessage:any) => any): HttpClient {
    this.ReponseInterceptor = interceptor;
    return this;
  }

  /**
   * 发起请求
   * @param requestMessage 请求体 
   */
  private Request(requestMessage:RequestMessage){ 
    var that = this;
    return new Promise((resolve,reject) => {
      if(that.RequestInterceptor && !that.RequestInterceptor(requestMessage))
        return reject("取消请求");
      wx.request({
        url: `${that.baseUrl}${requestMessage.Api}`,
        data:requestMessage.Param,
        method: requestMessage.Method,
        header:requestMessage.Header,
        success(res) {
          resolve && resolve(that.ReponseInterceptor && that.ReponseInterceptor(res));
        },
        fail(error){ 
          reject && reject(error);
         }
      });
    });
  }

  /**
   * Get 请求
   * @param api 接口
   * @param param 入参
   */
  public Get(api: string, param: any) {
    return this.Request(new RequestMessage(api,param));
  }

  /**
   * Head 请求
   * @param api 
   * @param param 
   * @returns 
   */
  public Head(api: string, param: any){
    return this.Request(new RequestMessage(api,param,HttpMethod.HEAD));
  }

  /**
   * Post 请求
   * @param api 接口 
   * @param param 入参
   */
  public Post(api: string, param: any){
    return this.Request(new RequestMessage(api,param,HttpMethod.POST));
  }

  /**
   * Connect 请求
   * @param api 
   * @param param 
   * @returns 
   */
  public Connect(api: string,param:any){
    return this.Request(new RequestMessage(api,param,HttpMethod.CONNECT));
  }

  /**
   * OPTIONS 请求
   * @param api 
   * @param param 
   * @returns 
   */
  public Options(api: string,param:any){
    return this.Request(new RequestMessage(api,param,HttpMethod.OPTIONS));
  }

  /**
   * Delete 请求
   * @param api 接口
   * @param param 入参
   */
  public Delete(api: string,param?: any){
    return this.Request(new RequestMessage(api,param,HttpMethod.DELETE));
  }

  /**
   * Put 请求
   * @param api 接口
   * @param param 入参
   */
  public Put(api: string, param: any){
    return this.Request(new RequestMessage(api,param,HttpMethod.PUT));
  }
}

/** HttpClient工厂 */
export class HttpClientFactory{
  public static Create(baseUrl:string = ''): HttpClient{
    return new HttpClient(baseUrl);
  }
}

使用方式

import { HttpClientFactory } from '../utils/request';

// 其他模块
import { StatusCode } from '../enums/httpstatus-enum';
import * as StorageConst from '../consts/storage-const';

// 配置基础地址
// export const client = HttpClientFactory.Create('http://121.196.126.53:5003/api/');
export const client = HttpClientFactory.Create('http://127.0.0.1:5000/api/');

/** 请求拦截器 */
client.UseRequestInterceptor(requestMessage => {
  if(requestMessage.Api !== "auth/login"){
    requestMessage.Header =  {
      "Authorization" : wx.getStorageSync(StorageConst.BearerToken)
    };
  }
  return true;
});

/** 响应拦截器 */
client.UseReponseInterceptor(reponseMessage => {
  reponseMessage&&console.log(reponseMessage);
  switch(reponseMessage.statusCode){  
    case StatusCode.StatusCode200Ok:
      return reponseMessage.data;
    case StatusCode.StatusCode401NotAuthorization:
      wx.redirectTo({ url :'../auth/login/index'});
      return;
      case StatusCode.StatusCode404NotFound:
      wx.showToast(reponseMessage.statusCode)
      return;
    default:
      return "状态码异常";
  }
});

封装接口

import { LoginInput } from './i-auth-service';
import { client } from '../http-client';
import * as StorageConst from '../../consts/storage-const';

/**
 * 
 * @param options 
 */
export function Login(options:LoginInput) {
  client.Post('auth/login',options).then(res => {
    wx.setStorageSync(StorageConst.BearerToken, `Bearer ${res.data}` );
    console.log(res);
  }).catch(reason => {
    console.log(reason);
  });
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值