微信小程序封装API接口

(1)在api/index.js文件中创建ReqClient

const API_HOST = 'https://xxx.xxx.com' //接口前缀
const ReqClient = (url, method, data) => {
  return new Promise((resolve, reject) => {
    wx.showLoading();
    if (method === 'GET') {
      var header = {
        'content-type': "application/x-www-form-urlencoded"
      }
    } else if (method === 'POST') {
      var header = {
        'content-type': 'application/json'
      }
    }
    wx.request({
      url: API_HOST + url,
      data,
      method,
      header: header,
      timeout: 6000,
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 500) {
          wx.showModal({
            title: '提示',
            content: '网络服务异常!',
            showCancel: false
          })
          reject(res);
        } else if (res.statusCode === 200) {
         if (res.data.code === 200) {
            resolve(res);
          } else {
            //业务处理
            reject(res);
          }
        } else {
          wx.showModal({
            title: '错误信息',
            content: '操作失败!如需帮助请联系技术人员',
            showCancel: false
          })
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showModal({
          title: '错误信息',
          content: '网络不可用,请检查你的网络状态或稍后再试!',
          showCancel: false
        })
        reject(err);
      }
    })
  })
}

(2)在api/user.js文件中使用ReqClient声明请求(也可以和第一步放在同一个文件中)
import {
  ReqClient
} from './index'

//检查用户登录状态
export const checkLoginStatus = (data) => {
  return ReqClient('/wx/auth/status', 'POST', {
    ...data
  })
}
(3)在业务代码中引入checkLoginStatus,就可以直接使用啦

import {
  checkLoginStatus
} from '../../api/user';
 
posted @ 2023-03-20 17:55  新手上线  阅读(176)  评论(0)    收藏  举报