飞道的博客

在vue中如何获取token,并将token写进header

1271人阅读  评论(0)
需要准备的东西:Vue+axios+Vuex+Vue-router
 
1.在login.vue中通过发送http请求获取token

 

 

    
  1. //根据api接口获取token
  2. var url = this.HOST + "/session";
  3. this.$axios.post(url, {
  4. username: this.loginForm.username,
  5. password: this.loginForm.pass
  6. }).then( res => {
  7. // console.log(res.data);
  8. this.$message.success( '登录成功');
  9. let data = res.data;
  10. //根据store中set_token方法将token保存至localStorage/sessionStorage中,data["Authentication-
  11. //Token"],获取token的value值
  12. this.$store.commit( 'set_token', data[ "Authentication-Token"]);
  13. if ( this.$store.state.token) {
  14. this.$router.push( '/')
  15. } else {
  16. this.$router.replace( '/login');
  17. }
  18. }).catch( error => {
  19. // this.$message.error(error.status)
  20. this.loading = false
  21. this.loginBtn = "登录"
  22. this.$message.error( '账号或密码错误');
  23. // console.log(error)
  24. })

 
 
2.在store.js中对token状态进行监管
 

    
  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. Vue.use(Vuex)
  4. export default new Vuex.Store({
  5. state:{
  6. token: ''
  7. },
  8. mutations:{
  9. set_token(state, token) {
  10. state.token = token
  11. sessionStorage.token = token
  12. },
  13. del_token(state) {
  14. state.token = ''
  15. sessionStorage.removeItem( 'token')
  16. }
  17. }
  18. })
 
3.在router/index.js中

   
  1. import Vue from 'vue'
  2. import Router from 'vue-router'
  3. import store from './store'
  4. // 页面刷新时,重新赋值token
  5. if (sessionStorage.getItem( 'token')) {
  6. store.commit( 'set_token', sessionStorage.getItem( 'token'))
  7. }
  8. const router = new Router({
  9. mode: "history",
  10. routes
  11. });
  12. router.beforeEach( (to, from, next) => {
  13. if (to.matched.some( r => r.meta.requireAuth)) { //这里的requireAuth为路由中定义的
  14. meta:{ requireAuth: true}, // 意思为:该路由添加该字段,表示进入该路由需要登陆的
  15. if (store.state.token) {
  16. next();
  17. } else {
  18. next({
  19. path: '/login',
  20. query: { redirect: to.fullPath}
  21. })
  22. }
  23. } else {
  24. next();
  25. }
  26. })

 
 
 
 
 
4.在main.js中定义全局默认配置:

 

Axios.defaults.headers.common['Authentication-Token'] = store.state.token;
 
5.在src/main.js添加拦截器,(先引入store.js)
 

    
  1. import Vue from 'vue'
  2. import Element from 'element-ui'
  3. import 'element-ui/lib/theme-chalk/index.css'
  4. import store from './store'
  5. import App from './App'
  6. import router from './router'
  7. import Axios from 'axios'
  8. // 添加请求拦截器
  9. Axios.interceptors.request.use( config => {
  10. // 在发送请求之前做些什么
  11. //判断是否存在token,如果存在将每个页面header都添加token
  12. if(store.state.token){
  13. config.headers.common[ 'Authentication-Token']=store.state.token
  14. }
  15. return config;
  16. }, error => {
  17. // 对请求错误做些什么
  18. return Promise.reject(error);
  19. });
  20. // http response 拦截器
  21. Axios.interceptors.response.use(
  22. response => {
  23. return response;
  24. },
  25. error => {
  26. if (error.response) {
  27. switch (error.response.status) {
  28. case 401:
  29. this.$store.commit( 'del_token');
  30. router.replace({
  31. path: '/login',
  32. query: { redirect: router.currentRoute.fullPath} //登录成功后跳入浏览的当前页面
  33. })
  34. break
  35. }
  36. }
  37. return Promise.reject(error.response.data)
  38. });
------------------------------------------------------------------------------------
...................完成以上步骤就可以了..........................
------------------------------------------------------------------------------------

 


转载:https://blog.csdn.net/qq_34825875/article/details/79569579
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场