提示:wx.request封装
一、app.js
代码如下(示例):
// app.js
App({
onLaunch() {
//查看环境
const accountInfo = wx.getAccountInfoSync();
this.globalData.envVersion = accountInfo.miniProgram.envVersion
},
globalData: {
envVersion:'', //环境变量
},
})
二、api/index.js
二次封装 wx.request
代码如下(示例):
const app = getApp();
//request合法域名
const URL = {
develop: {
baseUrl: "https://", //开发环境
},
trial: {
baseUrl: "https://", //体验版
},
release: {
baseUrl: "https://", //线上
}
}
let token = '获取token方式'
/**
* 二次封装wx.request
* url:请求的接口地址
* data:要传递的参数
* method:请求方式 GET,POST....
* isJson: 使用数据类型
*/
function request(url, data = {}, method = "GET", isJson = false) {
//看后端接口需求! 'content-Type'需要什么数据格式
// let contentType = method == 'POST' ? 'application/json' : 'application/x-www-form-urlencoded'
let contentType = isJson ? 'application/json' : 'application/x-www-form-urlencoded'
return new Promise(function (resolve, reject) {
wx.request({
url: URL[app.globalData.envVersion].baseUrl + url,
data: data,
method: method,
header: {
'content-Type': contentType,
'Authorization': token, //带上token
},
success: function (res) {
// console.log('res',res);
//逻辑处理
try {
//code === 1 请求成功
if (res.data.code === 1) {
resolve(res.data);
} else {
//请求错误
reject(res.data)
}
} catch (error) {
reject(error)
}
},
fail: function (err) {
//服务器连接异常
reject(err, "服务器连接异常,请检查网络再试")
}
})
});
}
/**
* GET请求封装
*/
function get(url, data = {}, isJson) {
return request(url, data, 'GET', isJson)
}
/**
* POST请求封装
*/
function post(url, data = {}, isJson) {
return request(url, data, 'POST', isJson)
}
// 暴露接口
module.exports = {
get,
post
}
三、页面使用
// index.js
const api = require('../../api/index');
Page({
data:{
carousel:[],
list:[]
},
onLoad() {
this.getList()
this.getCarousel()
},
/**
* 列表 POST请求
* {string}第一个参数 url
* {object}第二个参数 要传的数据
* {isJson}第三个参数 'content-Type'类型 , 填isJson为true,不填为false
*/
getList(){
let data ={
page:1,
pageSize: 10
}
api.post('/system/setting/list',data ,isJson).then(res => {
//请求成功
this.setData({
list: res.data.page
})
//其他
}).catch(err => { //错误提示
wx.showToast({
title: err.msg,
icon: "none"
})
},
/**
* 轮播图 GET 请求
* {string}第一个参数 url
* {object}第二个参数 要传的数据
* {isJson}第三个参数 'content-Type'类型 , 填isJson为true,不填为false
*/
getCarousel(){
api.get('/system/setting/carousel').then(res => {
//请求成功
this.setData({
background: res.data
})
//其他
}).catch(err=>{
wx.showToast({
title: err.msg,
icon: "none"
})
})
}
})
四、总结
综上所述,模式也好,技术也罢,没有好坏优劣之分,只有适合不适合;记录所学,分享所学…