1.新建api.js文件 写入
var sendRequest = function (url, method, data = {}, header = {}) {
var promise = new Promise(function (resolve, reject) {
wx.request({
url: url,
data: data,
method: method,
header: header,
success: function (data) {
//做一些统一处理操作,例如401验证
//resolve用于具体调用中
resolve(data);
},
fail: function (data) {
reject(data);
}
})
})
return promise
}
//导入
module.exports = {
sendRequest: sendRequest
}
2.在要使用的页面,在jsl里引入,使用
const api = require(’…/…/api/api’)
var that = this
api.sendRequest(app.globalData.API_URI, ‘GET’, {
cityname: ‘西安’,
key: app.globalData.MY_KEY,
})
.then(function (res) {
console.log(res)
that.setData({
city: res.data.result.today.city,
ymd: res.data.result.today.date_y,
week: res.data.result.today.week,
weather: res.data.result.today.weather,
dressing_index: res.data.result.today.dressing_index,
dressing_advice: res.data.result.today.dressing_advice,
uv_index: res.data.result.today.uv_index,
wash_index: res.data.result.today.wash_index,
travel_index: res.data.result.today.travel_index,
exercise_index: res.data.result.today.exercise_index,
})
}, function (error) {
wx.showLoading({
title: ‘网络异常’,
})
})
其中 app.globalData.API_URI 代表 请求接口 其他跟着文档走