这些天开始做小程序开发了在网络请求上发现了一些小问题,最终没忍住想了点办法把request封装了一下。下面来看看吧。
看项目代码时发现了下面几点问题:
网络请求都写在Page里,每个请求都要重复的写wx.request以及一些基础配置;
每个页面里都要处理相同类型的异常;
后端返的http status code为200以外时,并不能直接进入fail对应函数进行处理
针对这些问题,首先在项目utils目录里新建了一个http.js
const host = "http://www.week1.com:8888";
function request(url, data, method) {
return new Promise((resolve, reject) => {
wx.showLoading({
title: '加载中',
duration: 3000
})
wx.request({
url: host + url,
data: data || {},
header: {
'Content-Type': 'application/json;charset=UTF-8',
‘token’:wx.getStorageSync('token')
},
method: method || 'GET',
success: (res) => {
wx.hideLoading()
let statusCode = res.statusCode
if (statusCode === 200 ) {
resolve(res.data)
} else {
wx.showToast({
title: '网络异常,请检查网络状态',
icon: 'none',
duration: 3000
})
reject(res)
}
},
fail: (res) => {
wx.hideLoading()
wx.showToast({
title: '网络异常,请检查网络状态',
icon: 'none',
duration: 3000
})
reject(res)
}
})
})
}
module.exports={
request:request
}
之后在具体页面page.js直接对其进行引用
const http = require('../../utils/http');
test(){
http.request('/admin/vip/getdata')
},
成功!!!
const domain = "http://www.tp.com:8888";
export default class Https{
//刷新token
autoLogin(){
return new Promise((resolve,reject)=>{
wx.request({
url: 'http://www.week2.com:7888/api/autoToken',
success(res){
console.log(res.data)
wx.setStorageSync('token', res.data.token)
wx.setStorageSync('expire', res.data.expire)
}
})
})
}
request(url,data,method){
//获取token
var token = wx.getStorageSync('token')
//获取token过期时间
var expire = wx.getStorageSync('expire')
//当前时间戳
var timestamp = new Date().getTime()
var time = timestamp / 1000
// 如果过期时间 小于 当前时间 加 10 秒 则证明此token 已过期 准备提前刷新
if( parseInt(expire) - parseInt(time) < 10 ){
//调用刷新token接口 那时旧的token 还有效
this.autoLogin().then(()=>{
console.log(url)
this.request(url, data, method);
})
}
var header = {
'content-type': 'application/json'
}
if (token) {
header = {
'content-type': 'application/json',
'token':token
}
}
return new Promise((resolve,reject)=>{
wx.request({
url: domain+url,
data: data || {},
method: method ||'GET',
success: (result) => {
var statusCode = result.statusCode
if(statusCode !== 200){
wx.showToast({
title: '网络异常,请重试',
icon:"none",
duration:3000
})
}
resolve(result.data)
},
fail: (res) => {
wx.showToast({
title: '网络异常,请重试',
icon:"none"
})
reject(res)
}
})
})
}
}