路由拦截

项目中,有些页面需要登录后才能进入,例如,在某页面A,用户在操作前需要先进入登录页(此时需要将上一页的地址(/survey/start)作为query存入login页面的地址中,如: http://localhost:8071/#/login?redirect=%2Fsurvey%2Freport),登录成功后再进入页面A。

首先,在router.js中创建路由时,给需要登录的路由中的 meta 添加字段:requireLogin,如下:

const router = new Router({
routes: [
{
path: '/login',
name: 'Login',
component: Login,
meta: {
title: '登录页'
}
},
{
path: '/register',
name: 'Register',
component: Register,
meta: {
title: '注册页'
}
},
{
path: '/',
redirect: '/survey/start',
name: 'Full',
component: Full,
children: [
{
path: '/survey/start',
name: 'Home',
component: Home,
meta: {
title: '首页',
requireLogin: true
}
},
{
path: '/survey/report',
name: 'Report',
component: Report,
meta: {
title: '详情页',
requireLogin: true
}
}
]
}
]
})

然后使用 router.beforeEach 注册一个全局前置守卫:

// 全局导航钩子
router.beforeEach((to, from, next) => {
if (to.meta.title) { // 路由发生变化修改页面title
document.title = to.meta.title
}
if (to.meta.requireLogin) {
if (store.state.token) {
if (Object.keys(from.query).length === 0) { // 判断路由来源是否有query,处理不是目的跳转的情况
next()
} else {
let redirect = from.query.redirect // 如果来源路由有query
if (to.path === redirect) { // 避免 next 无限循环
next()
} else {
next({ path: redirect }) // 跳转到目的路由
}
}
} else {
next({
path: '/login',
query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
} else {
next()
}
})

关于Vue Router导航守卫,参考:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB

axios 请求拦截

上面的方法只是进行了前端拦截,无法确定存储在本地的token是否已经失效。需要 axios 拦截器:

在mian.js 中:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Axios from 'axios'
import './assets/styles/reset.css'
import './plugins/element.js'
import htmlToPdf from './utils/htmlToPdf' Vue.config.productionTip = false Vue.use(htmlToPdf) // http request 拦截器
Axios.interceptors.request.use(
config => {
if (sessionStorage.getItem('token')) { // 若存在token,则每个Http Header都加上token
config.headers.Authorization = `token ${sessionStorage.getItem('token')}`
}
return config;
},
err => {
return Promise.reject(err);
}) // http response 拦截器
Axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
// 返回 401 (未授权) 清除 token 并跳转到登录页面
sessionStorage.removeItem('token')
router.replace({
path: 'login',
query: {
redirect: router.currentRoute.fullPath
}
})
}
}
return Promise.reject(error.response.data) // 返回接口返回的错误信息
}
) new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')

vue 路由拦截、axios请求拦截的更多相关文章

  1. 前端快闪四: 拦截axios请求和响应

    马甲哥继续在同程艺龙写一点大前端: 今天我们来了解一下 如何拦截axios请求/响应? axios是一个基于 promise 的网络请求库,可以用于浏览器和 node.js, promise 类似于C ...

  2. vue/axios请求拦截

    import axios from 'axios';import { Message } from 'element-ui';import Cookies from 'js-cookie';impor ...

  3. vue中前端处理token过期的方法与axios请求拦截处理

    在处理token过期的这个问题上困扰了我很久,现在终于解决的了,所以分享出来给大家,希望能够对大家有所帮助. 首先,当然是路由进行拦截,路由拦截当然是在beforeEach中了: router.bef ...

  4. token回话保持,axios请求拦截和导航守卫以及token过期处理

    1:了解token:有时候大家又说token令牌.整个机制是前端第一次登陆发送请求,后端会根据前端的用户名和密码, 通过一些列的算法的到一个token令牌, 这个令牌是独一无二的,前端每次发送请求都需 ...

  5. axios请求,拦截器的使用

    1. axios 创建请求 import axios from 'axios' import {Message} from 'element-ui' import router from " ...

  6. vue脚手架用axios请求本地数据

    首先需要声明的是:本地请求,不用考虑跨域问题,这适用刚入坑的前端小白看,小白在做自己的项目时,通常都是用自己写的json数据,之后用axios请求过来,渲染到页面上. 1.cnpm install a ...

  7. axios请求拦截及请求超时重新请求设置

    自从使用Vue2之后,就使用官方推荐的axios的插件来调用API,在使用过程中,需要解决问题: 1. 请求带token校验 2. post请求请求体处理 3. 响应未登录跳转登录页处理 4. 响应错 ...

  8. axios请求拦截器

    import axios from 'axios';   // 创建axios实例   let service = null;   if (process.env.NODE_ENV === 'deve ...

  9. axios请求拦截器(修改Data上的参数 ==>把data上的参数转为FormData)

    let instance = axios.create({ baseURL: 'http://msmtest.ishare-go.com', //请求基地址 // timeout: 3000,//请求 ...

随机推荐

  1. 安装VisualSVN Server 报"Service 'VisualSVN Server' failed to start. Please check VisualSVN Server log in Event Viewer for more details"错误.原因是启动"VisualSVN Server"失败

    安装VisualSVN Server 报"Service 'VisualSVN Server' failed to start. Please check VisualSVN Server ...

  2. 第三章————用SQL语句操作数据

    第三章————用SQL语句操作数据 *********************新增**************************** 1. insert into 表名(列名1,列名2...) ...

  3. C#语言————第一章 第一个C#程序

    第一章    第一个C#程序 ******************C#程序***************     ①:建立项目:文件-->新建-->项目-->c#-->控制台程 ...

  4. Windows:添加、删除和修改静态路由

    添加一条路由 route add 删除一条路由 route add -p #作用同上,只是这是一条永久路由,不会因为重启机器而丢失.  注意:如果有两条路由记录有着相同的“目的网络号”,则会将两条记录 ...

  5. January 17th, 2018 Week 03rd Wednesday

    Don't let go too soon, but don't hold on too long. 不要太快放手,也别紧握太久. It is inevitalbe to encounter with ...

  6. 17秋 软件工程 团队第五次作业 Alpha Scrum9

    17秋 软件工程 团队第五次作业 Alpha Scrum9 今日完成的任务 世强:APP后端部门申请状态: 港晨:主页面代码实现: 树民:完善超级管理员web后端: 伟航:设置页面和侧边栏的原型: 陈 ...

  7. Sketch网页截屏插件设计开发

    1.需求 在Sketch的Artboard中插入网页截图: 1.1.输入网址,自动截图到Artboard中,并居中显示: 1.2.可截取网页局部图片 2.技术选型 技术的选型主要是针对截图功能的选型, ...

  8. SharePoint在管理中心创建Secure Store

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u012025054/article/details/35780063 SharePoint在管理中心 ...

  9. 转载 JavaScript的函数声明与函数表达式的区别

    1)函数声明(Function Declaration); // 函数声明 function funDeclaration(type){ return type==="Declaration ...

  10. ECharts.js学习动态数据绑定

    https://my.oschina.net/brillantzhao/blog/1541702https://www.cnblogs.com/leoxuan/p/6513591.htmlhttps: ...