本文重点
判断是不是微信环境
localstorage设置一个值
微信授权登录
获取一个时间戳 new Date().getTime()
const wx = (function () {
return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
})()
if (wx) {
const platformValue = 'wx'
localStorage.setItem('temp', platformValue) //如果现在是微信环境的话,做一个标识
}
const http = function (api, data = {}, withoutToken = false) {
// 拼接接口参数
const {
url,
method,
} = isObject(api) ? api : {
url: api,
method: 'post',
}
const accessToken = vuex.getters.getAccessToken
const v = '1.0'
const platform = localStorage.getItem('temp')
return axios({
url: withoutToken ? `${url}?platform=${platform}&v=${v}` : `${url}?accessToken=${accessToken}&platform=${platform}&v=${v}`,
method,
data,
}).catch(e => {
throw new Error('网络异常')
}).then(res => {
if (res.data.code === 502) {
this.$loadingEnd()
throw new Error('未登录')
} else if (res.data.code !== 200) {
throw new Error(res.data.message[0].details)
}
return res.data
})
}
export default http //这一段是封装了一个http
Vue.prototype.$errorHandler = function (err) {
if (err.message === '未登录') { //判断现在如果是未登录状态并且是微信环境跳转到下面的链接,即微信授权登录页面,传需要传的参数就可以了,拼接到后面即可
if (platform === 'wx') {
const path = encodeURIComponent(location.href)
location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx34284214d7a79ba1&redirect_uri=' + path + '&response_type=code&scope=snsapi_userinfo&state=' + new Date().getTime() + '#wechat_redirect')
} else {
this.$vux.toast.text('请先登录', 'middle')
this.$router.replace({ path: '/login' })
}
} else {
this.$vux.alert.show({
title: '鲸保科技提示',
content: `${err.message}`,
})
}
}