使用Vue在http请求头中添加token
用到的技术:Vue, Vue-router, axios, Vuex
1.在Login.vue中通过发送http请求获取token
//根据api接口获取token
submitForm (formName) {
this.$refs[formName].validate(valid => {
if (valid) {
this.$ajax.post('/login/signin', this.loginForm).then(res => {
if (res.data.returnCode === '100') { // ‘100’ 为自定义数据, 具体数值要和后端去统一商定
const loginData = res.data
const userInfo = res.data
this.form.username = userInfo.returnData.username
if (loginData.returnData.status === ' ') {
this.dialogVisible = true
} else {
const userInfo = res.data
localStorage.setItem('userInfo', JSON.stringify(userInfo))
this.$store.commit('set_token', res.headers.token)
this.$store.commit('changeHeadimg', userInfo.returnData.headimageurl)
this.$store.commit('changeUserInfo', JSON.stringify(userInfo))
this.$router.push('/')
}
} else {
this.$message({
message: res.data.returnMsg,
type: 'warning'
})
}
})
} else {
return false
}
})
},
2.在store.js中对token状态进行监管
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutation'
import actions from './action'
import getters from './getter'
Vue.use(Vuex)
const state = {
username: localStorage.getItem('userInfo') || {}, // 用户名
logined: JSON.parse(localStorage.getItem('userInfo')) || false, // 是否登录状态
token: '',
pdfModel: false,
headimageurl: ''
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
3.在router/index.js中将token添加到store中
import Vue from 'vue'
import Router from 'vue-router'
import store from '../vuex/store'
Vue.use(Router)
if (localStorage.getItem('token')) {
store.commit('set_token', localStorage.getItem('token'))
}
if (localStorage.getItem('headUrl')) {
store.commit('changeHeadimg', localStorage.getItem('headUrl'))
}
4.在main.js中定义全局的配置:
import axios from 'axios'
axios.defaults.baseURL = '/api' // 开发本地代理
axios.defaults.headers.post['Contenst-Type'] = 'application/json;'
axios.defaults.headers.common['token'] = store.state.token // 在header中添加token
Vue.config.productionTip = false
Vue.prototype.$ajax = axios
5.在src/main.js中添加必要的拦截器
if (localStorage.getItem('token')) {
store.commit('set_token', localStorage.getItem('token'))
}
const myfilter = {
bzdate: (date) => {
if (date) {
let timestring = new Date(date)
return timestring.toLocaleDateString() + ' ' + timestring.toTimeString().substr(0, 8)
}
}
}
for (let key in myfilter) {
Vue.filter(key, myfilter[key])
}
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
// 判断是否存在token,如果存在将每个页面header添加token
if (store.state.token) {
config.headers.common['token'] = store.state.token
}
return config
}, function (error) {
router.push('/login')
return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response
}, function (error) {
// 对响应错误做点什么
if (error.response) {
switch (error.response.status) {
case 401:
store.commit('del_token')
router.push('/login')
}
}
return Promise.reject(error)
})
router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title
}
if (to.path !== '/login' && !localStorage.getItem('userInfo')) {
next({path: '/login'})
} else {
next()
}
})
版权声明:本文为James_liPeng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。