API request in native WeChat applet

API request in native WeChat applet

When making API requests in native WeChat mini programs, encapsulating requests can improve the maintainability and scalability of the code. In this blog, we will walk through how to further encapsulate requests and add request timeouts, interceptors, and request cancellation functionality.

Insert image description here

Step One: Basic Request Encapsulation

First, we create a basic wrapper for sending HTTP requests. In the WeChat applet, we use to wx.requestsend requests, and here we encapsulate it into a Promise-style function:

// request.js

function request(url, method, data, header = {
     
     }) {
    
    
  return new Promise((resolve, reject) => {
    
    
    wx.request({
    
    
      url: url,
      method: method,
      data: data,
      header: {
    
    
        'content-type': 'application/json', // 根据需求设置请求头
        ...header,
      },
      success: (res) => {
    
    
        if (res.statusCode === 200) {
    
    
          resolve(res.data);
        } else {
    
    
          reject(new Error('请求失败'));
        }
      },
      fail: (err) => {
    
    
        reject(err);
      },
    });
  });
}

export function get(url, data = {
     
     }, header = {
     
     }) {
    
    
  return request(url, 'GET', data, header);
}

export function post(url, data = {
     
     }, header = {
     
     }) {
    
    
  return request(url, 'POST', data, header);
}

In this code, we define two functions getand post, which are used to send GET and POST requests respectively, and return a Promise to handle when the request succeeds or fails.

Step 2: Request timeout

In order to implement the request timeout function, we can use the Promise Promise.racemethod. We create a new Promise, set a timeout, and then compete it with the actual requested Promise. If the request is not completed within the timeout, we can cancel the request and throw a timeout error.

// request.js

function requestWithTimeout(url, method, data, header = {
     
     }, timeout = 5000) {
    
    
  return new Promise((resolve, reject) => {
    
    
    const timer = setTimeout(() => {
    
    
      reject(new Error('请求超时'));
    }, timeout);

    wx.request({
    
    
      url: url,
      method: method,
      data: data,
      header: {
    
    
        'content-type': 'application/json', // 根据需求设置请求头
        ...header,
      },
      success: (res) => {
    
    
        clearTimeout(timer);
        if (res.statusCode === 200) {
    
    
          resolve(res.data);
        } else {
    
    
          reject(new Error('请求失败'));
        }
      },
      fail: (err) => {
    
    
        clearTimeout(timer);
        reject(err);
      },
    });
  });
}

export function getWithTimeout(url, data = {
     
     }, header = {
     
     }, timeout = 5000) {
    
    
  return requestWithTimeout(url, 'GET', data, header, timeout);
}

export function postWithTimeout(url, data = {
     
     }, header = {
     
     }, timeout = 5000) {
    
    
  return requestWithTimeout(url, 'POST', data, header, timeout);
}

Step 3: Request interceptor and response interceptor

Interceptors allow us to perform some custom operations before the request is sent and after the response is returned, such as adding request headers, logging, or handling error messages. We can achieve this functionality by using function chains. First, we create two empty arrays requestInterceptorsand responseInterceptors, to store the interceptor functions. Then, we add interceptors through a function. Each interceptor is a function that accepts config(request configuration) or response(response object) as parameters and can modify them. Finally, on request or response, we execute them in sequence by looping through the array of interceptors.

// request.js

let requestInterceptors = [];
let responseInterceptors = [];

// 添加请求拦截器
export function addRequestInterceptor(interceptor) {
    
    
  requestInterceptors.push(interceptor);
}

// 添加响应拦截器
export function addResponseInterceptor(interceptor) {
    
    
  responseInterceptors.push(interceptor);
}

function executeInterceptors(interceptors, data) {
    
    
  return interceptors.reduce((prevData, interceptor) => {
    
    
    return interceptor(prevData);
  }, data);
}

function request(url, method, data, header = {
     
     }, timeout = 5000) {
    
    
  // ...
  
  // 执行请求拦截器
  config = executeInterceptors(requestInterceptors, config);
  
  // ...
  
  // 执行响应拦截器
  responseData = executeInterceptors(responseInterceptors, responseData);
  
  // ...
}

// ...

You can use addRequestInterceptorthe and addResponseInterceptorfunctions to add custom interceptors, for example:

import {
    
     addRequestInterceptor, addResponseInterceptor } from './request';

// 添加请求拦截器
addRequestInterceptor((config) => {
    
    
  // 在请求发出前进行一些操作,例如添加请求头
  config.header['Authorization'] = 'Bearer ' + getToken();
  return config;
});

// 添加响应拦截器
addResponseInterceptor((response) => {
    
    
  // 在响应返回后进行一些操作,例如处理错误信息
  if (response.statusCode !== 200) {
    
    
    throw new Error('请求失败');
  }
  return response.data;
});

Step Four: Request Cancellation

In order to implement the request cancellation function, we can use the Axios-style cancellation token (CancelToken). We need to create an CancelTokenobject and include it in the requested configuration. Then, where we need to cancel the request, we can call cancelthe method to cancel the request.

// request.js

let cancelToken = new wx.miniProgram.CancelToken();

function requestWithCancel(url, method, data, header = {
    
    }, timeout = 5000) {
    
    
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json', // 根据需求设置请求头
        ...header,
      },
      cancelToken: cancelToken.token, // 设置取消令牌
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(new Error('请求失败'));
        }
      },
      fail: (err) => {
    
    
        reject(err);
      },
    });
  });
}

// 取消请求
export function cancelRequest() {
    
    
  cancelToken.cancel('请求取消');
}
进一步封装请求超时、拦截器和请求取消功能可以提高代码的灵活性和可维护性。以下是一个更完整的原生微信小程序 API 请求封装,包括这些功能:

javascript
Copy code
// api.js

// 创建一个取消请求的 CancelToken
const CancelToken = wx.miniProgram.CancelToken;

// 默认配置
const defaultConfig = {
    
    
  baseURL: '', // 请求基础 URL
  timeout: 5000, // 请求超时时间(毫秒)
};

// 请求拦截器
function requestInterceptor(config) {
    
    
  // 在请求发送之前可以进行一些操作,例如添加请求头
  config.header = {
    
    
    'content-type': 'application/json',
    ...config.header,
  };
  return config;
}

// 响应拦截器
function responseInterceptor(response) {
    
    
  // 在收到响应后可以进行一些操作,例如处理错误信息
  if (response.statusCode !== 200) {
    
    
    throw new Error('请求失败');
  }
  return response.data;
}

// 创建请求实例
const instance = wx.request.create({
    
    
  timeout: defaultConfig.timeout,
  header: {
    
    
    'content-type': 'application/json',
  },
});

// 发送请求的函数
function sendRequest(config) {
    
    
  const {
    
     baseURL, timeout, ...restConfig } = {
    
     ...defaultConfig, ...config };
  const {
    
     url, method, data, params, cancelToken, ...otherConfig } = restConfig;

  // 合并请求 URL
  const fullURL = `${
     
     baseURL}${
     
     url}`;

  // 创建 CancelToken 实例
  const source = CancelToken.source();

  // 设置取消令牌
  otherConfig.cancelToken = source.token;

  // 发送请求
  return instance({
    
    
    url: fullURL,
    method,
    data,
    params,
    ...otherConfig,
  })
    .then(responseInterceptor)
    .catch((error) => {
      if (wx.miniProgram.isCancel(error)) {
    
    
        // 请求被取消
        console.log('请求已取消');
      } else {
    
    
        // 请求发生错误
        console.error('请求失败:', error);
      }
      throw error;
    });
}

export {
    
     sendRequest, requestInterceptor, responseInterceptor };

In the above code, the following functions are added:

  • Request timeout: You can specify the request timeout by setting timeout. If the request is not completed within the specified time, it will be cancelled.

  • Request interceptor and response interceptor: You can perform some custom operations before sending the request and after processing the response, such as adding request headers or handling error information.

  • Request cancellation: We use Axios' cancellation token (CancelToken) to support the request cancellation function. You can set cancelToken in the request configuration, and then call source.cancel() where the request needs to be canceled.

  • Using this further encapsulated request function sendRequest, you can handle network requests more flexibly in your project and perform customized operations in the interceptor to meet the needs of different scenarios. In the mini program page, import sendRequest and use it to initiate a request.
    Insert image description here
    The above is the API request in the native WeChat applet. Thank you all for reading.
    If you encounter other problems, you can discuss and learn with me privately.
    If it is helpful to you, please like and save it. Thank you~!
    Follow the favorite blog author for continuous updates...

Guess you like

Origin blog.csdn.net/qq2754289818/article/details/132900313