现在utils中新建一个request.js文件
request.js中的内容
const app = getApp();
module.exports = (url, data, method = "get", header = {}) => {
// loading动画 数据加载之前
var _loading = false
if (!_loading) {
wx.showLoading({
title: "Loading...",
mask: true
})
_loading = true
}
// 二次封装接口
return new Promise((resolve, reject) => {
wx.request({
url: app.globalData.url + url,
data,
method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header, // 设置请求的 header
success: resolve,
fail: reject,
complete: function () {
if (_loading) {
wx.hideLoading()
}
_loading = false
}
})
})
}
在app.js中写前缀
App({
globalData: {
url: "公共前缀",
}
})
在js中使用前引入
const app = getApp()
const request = require("../../utils/request")
使用方法
request("url").then(res => {
// console.log(res.data.data)
this.setData({
list: res.data.data
})
})