美文网首页
微信小程序请求封装

微信小程序请求封装

作者: xsmile21 | 来源:发表于2022-08-11 15:18 被阅读0次

util.js

const GET = 'GET';
const POST = 'POST';

const baseURL = ' ';  // 接口请求地址

function request(method, url, data) {
    return new Promise(function(resolve, reject) {
        let header = {
            'content-type': 'application/json'
        };
        wx.request({
            url: baseURL + url,
            method: method,
            data: method === POST ? JSON.stringify(data) : data,
            header: header,
            success(res) {
              console.log(res)
              // 请求到接口前页面展示loading
              wx.showLoading({
                title: '加载中...',
                success: function() {
                  // 请求成功
                  // 判断状态码,根据后端定义来判断
                  if (res.data.code == '200') {
                      resolve(res);
                  } else {
                      // 其他异常
                      reject('运行时错误,请稍后再试');
                      wx.showToast({
                        title: res.data.msg,
                        icon: 'none'
                      })
                  }
                }
              })
            },
            fail: function (err) {
              // 请求失败
              reject(err)
              wx.showToast({
                  title: '网络繁忙,请稍后重试~',
                  icon: 'none'
              })
             },
             complete: function () {
                // 配对使用(loading消失)
                wx.hideLoading();
             }
        })
    })
}

const API = {
  // 登录
  login: (data) => request(POST, `api地址`, data)
};

module.exports = {
  API: API
}

在需要使用到的页面:

const $api = require('../../utils/util.js').API;
$api.login().then(res => {
      console.log(res);
})

相关文章

网友评论

      本文标题:微信小程序请求封装

      本文链接:https://www.haomeiwen.com/subject/wrftgrtx.html