先对 wx.request() 进行基本的请求封装,再继续封装 post 和 get 请求
//在utils/http.js文件中
/**
* 请求相关的封装
*/
let baseUrl = "http://xxx.xxx.xx.xx:xx/"; // 接口地址
let header = {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': wx.getStorageSync("token")?wx.getStorageSync("token"):''
}
/**
* 封装请求
*/
function fetch(options) {
if (options.loading) {
wx.showLoading({
title: '加载中',
mask: true
})
}
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + options.url,
data: options.data,
header: header,
method: options.method,
success: function(res) {
if (options.loading) {
wx.hideLoading()
}
if (res.data.status != 0) { //根据自己的接口返回值进行判断
// 重新登陆
return false;
}
resolve(res.data); //把请求到的数据发到引用请求的地方
},
fail: function(err) {
if (options.loading) {
wx.hideLoading()
}
wx.showToast({
title: "网络连接超时",
icon: 'none',
duration: 3000,
})
}
})
})
}
/**
* POST 请求
*/
export function post(url, params, loading = true) {
var option = {
url: url,
data: params,
method: 'POST',
loading
}
return fetch(option);
}
/**
* GET请求
*/
export function get(urls, params, loading = true) {
var option = {
url: urls,
data: params,
method: 'GET',
loading
}
return fetch(option);
}
使用
//先通过模块化引入
const util = require('../../utils/util.js')
//get请求
http.get('getuserInfo', params).then((res) =>{
console.log(res)
})
//post请求
http.post('findDepartment', params).then( (res) =>{
console.log(res);
})
//也可以使用 async 和 await,比如
async formSubmit(e) {
let params = {
name:e.detail.value.name
passward:e.detail.value.passward
}
//let params = e.detail.value
const res = await http.post('login',params)
if(res.status===0){
//将token和用户信息存到本地
wx.setStorageSync('token', res.token);
wx.setStorageSync('userinfo', res.userinfo);
wx.showToast({
title: res.message,
icon: 'none',
duration: 3000
});
}
}