小程序封装的数据请求wx.request

172 阅读1分钟

request.js封装页面

export default function wxRequest(data, params, method) {
    const app = getApp();
    const baseUrl = app.globalData.baseUrl
    return new Promise((resolve, reject) => {
        wx.showLoading({
            title: '正在加载中',
            mask: true
        })
        wx.request({
            url: baseUrl + data,
            data: params,
            method: method ? method : "POST",
            header: {
                'content-type': 'application/json',
                'access_token': wx.getStorageSync('access_token')
            },
            success: res => {
                wx.hideLoading()
                if (res.data.code == 0) {
                    resolve(res)
                } else if (res.data.code == -1) {
                    wx.removeStorageSync('access_token')
                    app.wxLogin()
                    reject(res)
                } else {
                    wx.showModal({
                        title: '提示',
                        content: res.data.msg,
                        confirmColor: "#FF9829",
                        showCancel: false
                    })
                    reject(res)
                }
            },
            fail: err => {
                wx.hideLoading()
                wx.showModal({
                    title: '提示',
                    content: '网络错误,服务器请求失败',
                    confirmColor: "#FF9829",
                    showCancel: false
                })
            }
        })
    })
}

引用页面

import wxRequest from "../../utils/request"
const app = getApp();

模拟接口

wxRequest(`Order/AuditFailure?id=${this.data.auditid}`, {}, "POST").then(res => {

})