const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const baseURL = 'url';//写上自己的请求基础路径
function request(method, url, data, headerParam) {
return new Promise(function (resolve, reject) {
const cookie = wx.getStorageSync('cookie') || ''
let header = {
'Content-type': headerParam ? headerParam : 'application/x-www-form-urlencoded;charset=utf-8',
'cookie': cookie
};
wx.request({
url: baseURL + url,
method: method,
data: data,
header: header,
success(res) {
if (res.header["Set-Cookie"]) {
wx.setStorageSync('cookie', res.header["Set-Cookie"]) // 从返回数据的响应头中取cookie
}
//请求成功
// 判断状态码---code状态根据后端定义来判断
if (res.data.code == 1000) {
resolve(res);
} else {
//其他异常
wx.showToast({
title: res.data.msg,
icon: 'none',
duration: 2000
})
let pages = getCurrentPages()
let nowPage = pages[0].__route__
if (res.data.msg === '请登录后再访问!') {
if(nowPage!=='pages/login/login'){
setTimeout(() => {
wx.navigateTo({
url: '/pages/login/login',
})
}, 2000)
}
}
reject(res);
}
},
fail(err) {
//请求失败
reject(err)
}
})
})
}
function requestSpecial(method, url, data, headerParam) {
return new Promise(function (resolve, reject) {
const cookie = wx.getStorageSync('cookie') || ''
let header = {
'Content-type': headerParam ? headerParam : 'application/x-www-form-urlencoded;charset=utf-8',
'cookie': cookie
};
wx.request({
url: baseURL + url,
method: method,
data: data,
header: header,
responseType: 'arraybuffer',
success(res) {
if (res.header["Set-Cookie"]) {
wx.setStorageSync('cookie', res.header["Set-Cookie"]) // 从返回数据的响应头中取cookie
}
resolve(res)
},
fail(err) {
//请求失败
reject(err)
}
})
})
}
function params(obj) {
let result = '';
let item;
for (item in obj) {
if (obj[item] && String(obj[item])) {
result += `&${item}=${obj[item]}`;
}
}
if (result) {
result = '?' + result.slice(1);
}
return result;
}
const API = {
get: (url, data, headerParam) => request(GET, `${url}${params(data)}`, headerParam),
getRESTful: (url, data, headerParam) => request(GET, url, data, headerParam),
getSpecial: (url, data, headerParam) => requestSpecial(GET, `${url}${params(data)}`, headerParam),
post: (url, data, headerParam) => request(POST, url, data, headerParam),
put: (url, data, headerParam) => request(PUT, url, data, headerParam),
};
module.exports = {
API: API
}
小程序请求封装
最新推荐文章于 2024-04-06 20:30:52 发布