Vue中保存token以及删除设置token
import Cookies from 'js-cookie'const TokenKey = 'vue_admin_template_token'export function getToken() {return Cookies.get(TokenKey)}export function setToken(token) {return Cookies.set(TokenKey, token)}
·
import Cookies from 'js-cookie'
const TokenKey = 'vue_admin_template_token'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
return Cookies.remove(TokenKey)
}
拦截器
// 创建一个axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true,跨域请求时发送cookies
timeout: 5000 // request timeout
})
// 请求拦截器
import axios from 'axios'
import store from '@/store'
import Vuex from 'vuex'
const store = new Vuex.Store({
modules: {
app,
settings,
user
},
getters
})
service.interceptors.request.use(
config => {
// 在发送请求之前做一些事情
if (store.getters.token) {
// 让每个请求都携带token
// ['X-Token'] 是自定义标题键
// 请根据实际情况修改
config.headers['X-Token'] = getToken()
}
return config
},
error => {
// 处理请求错误
console.log(error) // 用于调试
return Promise.reject(error)
}
)
更多推荐
已为社区贡献3条内容
所有评论(0)