安装
首先安装flyio,通过命令:
npm install flyio -S
例如在request.js中:
import Fly from 'flyio/dist/npm/wx'
var fly = new Fly()
var newfly = new Fly()
请求配置选项
请求配置可以通过fly中的config来设置,例如一些通用配置如下:
//定义公共headers
fly.config.headers={
'content-type': 'application/json',
'token': 'xxxxxx'
}
//设置超时
fly.config.timeout=10000;
//设置请求基地址
fly.config.baseURL="https://你的域名/"
拦截器
import Fly from 'flyio/dist/npm/wx'
var fly = new Fly()
var newfly = new Fly()
fly.config.baseURL = "https://你的域名/"
newfly.config.baseURL = "https://你的域名/"
fly.interceptors.request.use(async function (request) {
request.timeout = 30000
if (wx.getStorageSync('token') && wx.getStorageSync('token_expiration') > Date.parse(new Date())) {
request.headers = {
'content-type': 'application/json',
'token': wx.getStorageSync('token')
}
} else {
fly.lock()
const login = await getToken()
wx.setStorageSync('token', login.data.data)
wx.setStorageSync('token_expiration', Date.parse(new Date()) + 50000)
request.headers = {
'content-type': 'application/json',
'token': login.data.data
}
fly.unlock()
}
return request
})
fly.interceptors.response.use(async (response) => {
return response
}, (err) => {
console.log(err)
var title = ''
if (err.status === 0) {
title = '网络连接异常'
} else if (err.status === 1) {
title = '网络连接超时'
} else if (err.status === 401) {
wx.removeStorageSync('token')
wx.removeStorageSync('token_expiration')
title = '登录超时,请重试'
} else {
title = err.response.data.message ? err.response.data.message : '请求数据失败,请稍后再试'
}
return wx.showToast({
title: title,
icon: 'none',
duration: 2000
})
})
const getToken = async () => {
return new Promise((resolve) => {
wx.login({
async success (loginRes) {
console.log(loginRes)
if (loginRes.code) {
await newfly.get('login/getToken', {
code: loginRes.code
}).then((flyReq) => {
console.log('token请求成功' + flyReq)
resolve(flyReq)
})
} else {
console.log('登录失败!' + loginRes.errMsg)
}
}
})
})
}
export default fly