request.js,在api文件引入
import axios from 'axios'
// 创建 axios 实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 60000, // 请求超时时间
withCredentials: true,
headers: {
'cache-control': 'no-cache',
'Pragma': 'no-cache'
}
})
export default service
init-auth.js---axios封装/路由检查,在main.js里引入
import router from '@/router/index'
import store from '@/store/index'
import requestv2 from '@/utils/request'
import _set from "lodash.set"
import _get from "lodash.get"
import accessToken from '@/utils/access_token'
// import {Base64} from "js-base64"// 不兼容ie
import {Message} from 'element-ui'
/**
* 请求检查
*/
function handleUnauthorized() {
store.dispatch('LOG_OUT')// 退出
}
requestv2.interceptors.request.use((config) => {
let token = accessToken.getToken()
_set(config, 'headers.Authorization', `Bearer ${token}`)
return config
})
requestv2.interceptors.response.use((res) => {
// 不需要拦截的走这里
if (_get(res, 'config.raw')) {
return res
}
const code = _get(res, 'data.Code')
switch (code) {
case 0:
case 200:
return _get(res, 'data.Data')
case 100:
case 101:
case 102:
case 103:
case 104:
case 105:
case 110:
return handleUnauthorized()
case 400:
const msg = _get(res, 'data.Msg', '')
Message.error(msg)
return Promise.reject(msg)
default:
const e = new Error(_get(res, 'data.Msg', ''))
e.code = _get(res, 'data.Code')
return Promise.reject(e)
}
}, (error) => {
const status = _get(error, 'response.status')
if (status === 401 || status === 403) {
return handleUnauthorized()
}
return Promise.reject(error)
})
/**
* 路由检查
*/
router.beforeEach(((to, from, next) => {
if (to.meta.requireAuth === false) {
return next()
}
const profile = accessToken.getProfile() // 保存的token
if (Date.now() / 1000 >= _get(profile, 'exp')) {
Message.error('登录超时,请重新登录')
const redirect = `${process.env.VUE_APP_BUYER_URL}${to.fullPath}`
window.location.href = `${process.env.VUE_APP_UC_URL}login?redirect=${encodeURIComponent(redirect)}`
}
next()
}))
access_token.js--存取token
import cookie from 'js-cookie'
import jwt from 'jsonwebtoken'
export class AccessToken {
name = ''
domain = ''
constructor(name, domain) {
this.name = name
this.domain = domain
}
getToken() {
return cookie.get(this.name)
}
setToken(token) {
cookie.set(this.name, token, {domain: this.domain})
}
getProfile() {
try {
return jwt.decode(this.getToken())
} catch (e) {
return null
}
}
}
const m = new AccessToken('USER_ACCESS_TOKEN', process.env.VUE_APP_TOP_DOMAIN)
export default m
网友评论