路由拦截

项目中,有些页面需要登录后才能进入,例如,在某页面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. python第五十四天--第十周作业

    SELECT版FTP:使用SELECT或SELECTORS模块实现并发简单版FTP允许多用户并发上传下载文件 必须使用select or selectors模块支持多并发,禁止使用多线程或多进程 RE ...

  2. php把阿拉伯数字转为银行数字大写

    php把阿拉伯数字转为银行数字大写 前言:之前在做一个外贸公司的询报价系统时用到了记录关于金额的数据,一般阿拉伯数字都需要转为银行使用的大写数字,在这简单记录一下 /* * 数字金额转换成中文大写金额 ...

  3. 50个常用sql语句 网上流行的学生选课表的例子

    50个常用sql语句 建表: --学生表tblStudent(编号StuId.姓名StuName.年龄StuAge.性别StuSex) --课程表tblCourse(课程编号CourseId.课程名称 ...

  4. Spring boot+ maven + thymeleaf + HTML 实现简单的web项目

    第一步: 创建一个SpringBoot应用 第二步: 创建一个实体,用来存储数据,在src/main/java/com/example/first下创建包entity , 在entity下创建Pers ...

  5. String类的常用方法详解

    1:获取字符串的长度length(),下标从1开始 2:将其他类型转换为String类型toStrings() 3:去除字符串首尾的空格trim() 4:分割字符串spilt() 5:比较两个字符串是 ...

  6. SqlBulkCopy批量添加

    /// <summary> /// 添加数据 /// 注:DataTable列名必须和数据库列名一致 /// </summary> /// <returns>< ...

  7. 离线安装PostgreSQL

    postgresql在线安装很简单,但是很多情况,服务器不能联网,需要离线安装.下面是离线安装的步骤: 1. 首先进入官网: https://www.postgresql.org/ 2. 点击Down ...

  8. Django之views

    一 URL补充 二 Views试图函数 一 URL补充 1 MTV模型 2  django建立流程(用命令版) (1)django-admin startproject projectname (2) ...

  9. 使用hint优化Oracle的运行计划 以及 SQL Tune Advisor的使用

    背景: 某表忽然出现查询很缓慢的情况.cost 100+ 秒以上:严重影响生产. 原SQL: explain plan for select * from ( select ID id,RET_NO ...

  10. java list 排序,建议收藏的排序方法

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code public static void main(String[] args) {    ...