微信小程序请求封装

1. 基于promise封装request.js

const baseURL = 'http://api.xxxxxx.cn/';

export function request(method, url, data) {
  return new Promise(function (resolve, reject) {
    let header = data.header || {}
    header["content-type"] = "application/json";
    let userInfo = getApp().globalData.userInfo
    if (userInfo) {
      header["session_id"] = userInfo.session_id;
    }

    wx.request({
      url: baseURL + url,
      method: method,
      data: data || {},
      header: header,
      success(res) { //请求成功
        if (res.statusCode == 401) {
          // 重定向到登录授权页
          wx.redirectTo({
            url: `/pages/index/index?target=${encodeURIComponent('/pages/main/main')}`
          });
          return;
        }
        resolve(res.data);
      },
      fail(err) { //请求失败
        reject(err)
      }
    })
  })
}

2. 基于request建立请求列表

import { request } from './request';

const API = {
  getOpenid: (data) => request('get', 'dashboard/boss/simple',data),
};

module.exports = {
  API
}

3. 在文件中引入使用(下面为ts文件)

    const { API } = require('../../utils/apiList');

    API.getOpenid({businessId: '123'}).then((res:any)=>{
      console.log(res)
    }).catch(err=>{
      console.log(err) 
    })

 

posted on 2021-03-11 12:29  活在当下zql  阅读(419)  评论(0)    收藏  举报