概要
wx.request()方法不支持Promise风格的调用方式,且无法使用拦截器、baseUrl等功能,我根据自己的使用习惯,对其进行简单封装。
封装代码:
const http = {
defaults: {
baseUrl: 'http://localhost:8081/micronews/v1',
timeout: 60000,
method: 'GET',
data: null,
header: { 'Content-type': 'application/json' }
},
interceptors: {
request: config => {
wx.showLoading({
title: '数据加载中。。。'
})
return config
},
response: res => {
wx.hideLoading()
console.log(res)
if (!res.isSuccess) {
wx.showToast({
title: '网络错误',
icon: 'error'
})
return res
}
switch (res.data.code) {
case '0':
break
default:
wx.showToast({
title: '错误码:' + res.data.code,
icon: 'error'
})
throw new Error('错误')
}
return res.data
}
},
request(opt) {
let opts = { ...this.defaults, ...opt }
opts.url = opts.baseUrl + opts.url
opts = this.interceptors.request(opts)
return new Promise((rs, rj) => {
wx.request({
...opts,
success: res => {
const rres = this.interceptors.response({ ...res, config: opts, isSuccess: true })
return rs(rres)
},
fail: res => {
const rres = this.interceptors.response({ ...res, config: opts, isSuccess: false })
return rj(rres)
}
})
})
},
get(url, data = {}, config = {}) {
return this.request({ url, data, method: 'GET', ...config })
},
post(url, data = {}, config = { header: { 'Content-type': 'application/x-www-form-urlencoded' } }) {
return this.request({ url, data, method: 'POST', ...config })
}
}
wx.$apis = {
getNewsList: () => http.get('/news'),
getNews: id => http.get('/news/' + id),
getMyNews: id => http.get('/news/user/' + id),
login: data => http.post('/user/login', data),
signup: data => http.post('/user/signup', data),
publish: data => http.post('/news/publish', data),
changeName: data => http.post('/user/1', data)
}
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute].map(formatNumber).join(':')}`
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : `0${n}`
}
wx.formatTime = formatTime
技术细节
提示:注意,这里没有使用模块化暴露的方式进行封装,而是直接将apis加载到wx全局对象上,这样,只需要在app.js里引入一次,即可全局使用,更加便捷。使用同样的方式,也可以把app.js中的全局数据直接挂载到wx全局对象上。app.js的代码如下:
// app.js
// import "./utils/axios"
import './utils/http'
// import './utils/util'
App({
onLaunch() {
// 获取登录状态
const user = wx.getStorageSync('user')
if (user) {
this.globalData.logined = true
this.globalData.user = user
}
wx.$app = this
wx.$data = this.globalData
wx.$user = wx.$data.user
},
globalData: {
user: null,
logined: false,
newsList: []
}
})
可以看到我们挂载了formatTime、$apis、$app、$data等全局数据,一次挂载,全局使用