promise封装微信小程序的request
1、在utils下创建一个 request.js文件,然后将方法导出
const app = getApp(); //使用promise封装request请求 const POST = (url, params) => { let promise = new Promise((resolve, reject) => { wx.request({ url: url, data: params, header:'application/x-www-form-urlencoded', // 默认值 method: "POST", success: res => { console.log("返回结果:"); console.log(res.data); app.netWorkData.result = res.data; resolve(); }, fali: res => { reject(res); } }); }); return promise; }; module.exports = { POST: POST };
2、app.js
App({ netWorkData: { result: { code: -1, msg: '发起请求失败' } }, })
3、在需求请求数据的js文件中先引入request.js文件
const request = require('../../utils/request.js');
调用,发送请求
onLoad: function (options) { const that = this; var url = apiUrl + 'api/info/querydetail'; var params={ "id": options.id, // 该条信息的id "uid": "", // 当前用户id,可以不填写 "lat": lat, // 纬度 默认是杭州的维度 "lng": long, } network.POST(url, params).then(() => { //请求成功的操作 var _data = app.netWorkData.result; that.setData({ list: _data.data, id: _data.data.id }); }); },