本文重點
判斷是不是微信環境
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}`,
})
}
}