微信小程序封装request
1. 首先在微信小程序管理后台中注册域名
2. 方法封装:在utils文件夹下创建uitl.js文件,用于对方法封装;创建api.js文件,用于对第二层封装的Promise;
util.js
const baseUrl = "http://127.0.0.0.1:8888";//请求域名
const $get = async function(url, data, success, fail, power) {
if (url.indexOf('http') == -1) {
url = baseUrl + url
}
var header = {};
header['content-type'] = "application/x-www-form-urlencoded";
if (power) {
var token = wx.getStorageSync('token');
header['authorization'] = token;
}
if (data) {
data = "?" + qs.stringify(data);
url += data;
}
wx.request({
url,
method: 'GET',
header,
success(res) {
// console.log('原始数据===',res)
if (res.statusCode == 200) {
if(res.data.code == 401) {
wx.navigateTo({
url: '/pages/login/login',
})
}
success && success(res.data)
} else {
fail && fail(res)
}
},
fail(res) {
fail && fail(res)
}
})
}
const $post = function(url, data,success,fail, power, contentType, responseType = false) {
if (url.indexOf('http') == -1) {
url = baseUrl + url
}
var header = {};
header['content-type'] = "application/x-www-form-urlencoded";
if (contentType) {
header['content-type'] = contentType;
}
if (power) {
var token = wx.getStorageSync('token');
header['authorization'] = token;
}
if (data) {
console.log("data====",data)
} else {
data = null;
}
wx.request({
url,
method: 'POST',
data,
header,
responseType,
success(res) {
if (res.statusCode == 200) {
if(res.data.code == 401) {
wx.navigateTo({
url: '/pages/login/login',
})
}
success && success(res.data)
} else {
fail && fail(res)
}
},
fail(res) {
fail && fail(res)
}
})
}
api.js
const utils = require('./util.js');
const goods = {
async get_goods(goods_id) {
return await new Promise((resolve, reject) => {
utils.$post("/api/goods/get_goods", {
goods_id
}, res => {
resolve(res)
}, res => {
reject(res)
})
})
},
},
调用时,具体哪个页面需要用到,在调用函数:const app = getApp();然后调用api.js里面的函数发起请求。
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.get_good()
},
get_good(){
app.$api.get_goods().then(res=>{
console.log(res)
if(res.code==200){
console.log(res)
}else{
wx.showToast({
title:res.msg,
icon:'error'
})
}
}).catch(res=>{
console.log(res);
wx.showToast({
title:res.msg,
icon:''
})