需求及实现

  • 统一捕获接口报错
  • 弹窗提示
  • 报错重定向
  • 基础鉴权
  • 表单序列化

用法及封装

用法

// 服务层 , import默认会找该目录下index.js的文件,这个可能有小伙伴不知道可以去了解npm的引入和es6引入的理论概念
import axiosPlugin from "./server";
Vue.use(axiosPlugin);

对axios的封装(AXIOS:index.js)

import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";
import router from "../router"; const Axios = axios.create({
baseURL: "/", // 因为我本地做了反向代理
timeout: ,
responseType: "json",
withCredentials: true, // 是否允许带cookie这些
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
}
}); //POST传参序列化(添加请求拦截器)
Axios.interceptors.request.use(
config => {
// 在发送请求之前做某件事
if (
config.method === "post" ||
config.method === "put" ||
config.method === "delete"
) {
// 序列化
config.data = qs.stringify(config.data);
} // 若是有做鉴权token , 就给头部带上token
if (localStorage.token) {
config.headers.Authorization = localStorage.token;
}
return config;
},
error => {
Message({
// 饿了么的消息弹窗组件,类似toast
showClose: true,
message: error,
type: "error.data.error.message"
});
return Promise.reject(error.data.error.message);
}
); //返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
res => {
//对响应数据做些事
if (res.data && !res.data.success) {
Message({
// 饿了么的消息弹窗组件,类似toast
showClose: true,
message: res.data.error.message.message
? res.data.error.message.message
: res.data.error.message,
type: "error"
});
return Promise.reject(res.data.error.message);
}
return res;
},
error => {
// 用户登录的时候会拿到一个基础信息,比如用户名,token,过期时间戳
// 直接丢localStorage或者sessionStorage
if (!window.localStorage.getItem("loginUserBaseInfo")) {
// 若是接口访问的时候没有发现有鉴权的基础信息,直接返回登录页
router.push({
path: "/login"
});
} else {
// 若是有基础信息的情况下,判断时间戳和当前的时间,若是当前的时间大于服务器过期的时间
// 乖乖的返回去登录页重新登录
let lifeTime =
JSON.parse(window.localStorage.getItem("loginUserBaseInfo")).lifeTime *
;
let nowTime = new Date().getTime(); // 当前时间的时间戳
console.log(nowTime, lifeTime);
console.log(nowTime > lifeTime);
if (nowTime > lifeTime) {
Message({
showClose: true,
message: "登录状态信息过期,请重新登录",
type: "error"
});
router.push({
path: "/login"
});
} else {
// 下面是接口回调的satus ,因为我做了一些错误页面,所以都会指向对应的报错页面
if (error.response.status === ) {
router.push({
path: "/error/403"
});
}
if (error.response.status === ) {
router.push({
path: "/error/500"
});
}
if (error.response.status === ) {
router.push({
path: "/error/502"
});
}
if (error.response.status === ) {
router.push({
path: "/error/404"
});
}
}
}
// 返回 response 里的错误信息
let errorInfo = error.data.error ? error.data.error.message : error.data;
return Promise.reject(errorInfo);
}
); // 对axios的实例重新封装成一个plugin ,方便 Vue.use(xxxx)
export default {
install: function(Vue, Option) {
Object.defineProperty(Vue.prototype, "$http", { value: Axios });
}
};

路由钩子的调整(Router:index.js)

import Vue from "vue";
import Router from "vue-router";
import layout from "@/components/layout/layout";
// 版块有点多,版块独立路由管理,里面都是懒加载引入
import customerManage from "./customerManage"; // 客户管理
import account from "./account"; //登录
import adManage from "./adManage"; // 广告管理
import dataStat from "./dataStat"; // 数据统计
import logger from "./logger"; // 日志
import manager from "./manager"; // 管理者
import putonManage from "./putonManage"; // 投放管理
import error from "./error"; // 服务端错误
import { Message } from "element-ui"; Vue.use(Router); // 请跳过这一段,看下面的
const router = new Router({
hashbang: false,
mode: "history",
routes: [
{
path: "/",
redirect: "/adver",
component: layout,
children: [
...customerManage,
...adManage,
...dataStat,
...putonManage,
...manager,
...logger
]
},
...account,
...error
]
}); // 路由拦截
// 差点忘了说明,不是所有版块都需要鉴权的
// 所以需要鉴权,我都会在路由meta添加添加一个字段requireLogin,设置为true的时候
// 这货就必须走鉴权,像登录页这些不要,是可以直接访问的!!!
router.beforeEach((to, from, next) => {
if (to.matched.some(res => res.meta.requireLogin)) {
// 判断是否需要登录权限
if (window.localStorage.getItem("loginUserBaseInfo")) {
// 判断是否登录
let lifeTime =
JSON.parse(window.localStorage.getItem("loginUserBaseInfo")).lifeTime *
;
let nowTime = (new Date()).getTime(); // 当前时间的时间戳
if (nowTime < lifeTime) {
next();
} else {
Message({
showClose: true,
message: "登录状态信息过期,请重新登录",
type: "error"
});
next({
path: "/login"
});
}
} else {
// 没登录则跳转到登录界面
next({
path: "/login"
});
}
} else {
next();
}
}); export default router;

axios可配置的一些选项,

export default {
// 请求地址
url: "/user",
// 请求类型
method: "get",
// 请根路径
baseURL: "http://www.mt.com/api",
// 请求前的数据处理
transformRequest: [function(data) {}],
// 请求后的数据处理
transformResponse: [function(data) {}],
// 自定义的请求头
headers: { "x-Requested-With": "XMLHttpRequest" },
// URL查询对象
params: { id: },
// 查询对象序列化函数
paramsSerializer: function(params) {},
// request body
data: { key: "aa" },
// 超时设置s
timeout: ,
// 跨域是否带Token
withCredentials: false,
// 自定义请求处理
adapter: function(resolve, reject, config) {},
// 身份验证信息
auth: { uname: "", pwd: "" },
// 响应的数据格式 json / blob /document /arraybuffer / text / stream
responseType: "json",
// xsrf 设置
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-XSRF-TOKEN", // 下传和下载进度回调
onUploadProgress: function(progressEvent) {
Math.round(progressEvent.loaded * / progressEvent.total);
},
onDownloadProgress: function(progressEvent) {}, // 最多转发数,用于node.js
maxRedirects: ,
// 最大响应数据大小
maxContentLength: ,
// 自定义错误状态码范围
validateStatus: function(status) {
return status >= && status < ;
},
// 用于node.js
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }), // 用于设置跨域请求代理
proxy: {
host: "127.0.0.1",
port: ,
auth: {
username: "aa",
password: ""
}
},
// 用于取消请求
cancelToken: new CancelToken(function(cancel) {})
};

写在最后

我这个封装虽说不是万金油版本,但是我感觉大多用axios结合vue的小伙伴, 稍微改改都能直接拿来用

Vue 给axios做个靠谱的封装(报错,鉴权,跳转,拦截,提示)的更多相关文章

  1. axios interceptors 拦截 , 页面跳转, token 验证 Vue+axios实现登陆拦截,axios封装(报错,鉴权,跳转,拦截,提示)

    Vue+axios实现登陆拦截,axios封装(报错,鉴权,跳转,拦截,提示) :https://blog.csdn.net/H1069495874/article/details/80057107 ...

  2. vue.js环境配置步骤及npm run dev报错解决方案

    安装完成后,使用npm run dev 运行,成功后,就可以在浏览器中看到vue的欢迎画面了 最后一步可能报错,我就遇到这样的问题了, 个人问题仅供参考: ERROR Failed to compil ...

  3. SAP 对HU做转库操作,系统报错 - 系统状态HUAS是活动的 - 分析

    SAP 对HU做转库操作,系统报错 - 系统状态HUAS是活动的 - 分析 近日收到业务团队报的问题,说是对某个HU做转库时候,系统报错.如下图示: HU里有是三个序列号, 1191111034011 ...

  4. vue使用Axios做ajax请求

    vue2.0之后,就不再对vue-resource更新,而是推荐使用axios 1. 安装 axios $ npm install axios 或 $ bower install axios 2. 在 ...

  5. vue 项目项目启动时由于EsLint代码校验报错

    今天在编写好vue项目代码时,在命令行输入npm start的时候出现了如下图所示的一大堆错误: 在网上查找资料说是缺少EsLint配置文件的问题,最终找到一篇由 hahazexia 编写的一篇博客文 ...

  6. vue开发的项目中遇到的警告,报错,配置项目文件等合集(长期更新)

    1. Vue组件里面data()里面没有return时触发错误:Vue components Cannot read property '__ob__' of undefined 这个警告不解决会触发 ...

  7. Vue项目用了脚手架vue-cli3.0,会报错You are using the runtime-only build of Vue where the template compiler is not available.....

    摘自: https://blog.csdn.net/wxl1555/article/details/83187647 报错信息如下图: 报错原因是:vue有两种形式的代码:一种是compiler(模版 ...

  8. Vue常见问题解决办法(一)ESLint检查报错

    vue.js报错“Do not use 'new' for side effects“(main.js里)解决办法 ESLint工具检查代码质量,main.js里的原代码是这样的: new Vue({ ...

  9. Vue+DataTables warning:table id=xxxx -Cannot reinitialize DataTable.报错解决方法

    问题描述: 使用DataTables来写列表,用vue来渲染数据,有搜索功能,每次点击搜索就会报错,如下图所示. 问题排查: 找了一系列原因,最后发现是我每次请求完数据之后都会添加分页功能,从而导致了 ...

随机推荐

  1. 2018-2019-2 网络对抗技术 20165305 Exp2 后门原理与实践

    常用后门工具 一.Windows获得Linux Shell 在Windows下使用ipconfig查看本机IP 使用ncat.exe程序监听本机的5305端口 在Kali环境下,使用nc指令的-e选项 ...

  2. Python 较为完善的猜数字游戏

    import random def guess_bot(): bot = random.randint(1, 100) # time = int(input("你觉得能猜对需要的次数:&qu ...

  3. 【winform】splitContainer拆分器控件

    一. 1.panel的显示和隐藏 设置SplitterDistance的数值大小即可改变panel的左右大小.这里设置的数值是指分割线距离左边框的像素,设置成0的话,左半部分就完全看不到了,可以实现一 ...

  4. Python-----多线程threading用法

    threading模块是Python里面常用的线程模块,多线程处理任务对于提升效率非常重要,先说一下线程和进程的各种区别,如图 概括起来就是 IO密集型(不用CPU) 多线程计算密集型(用CPU) 多 ...

  5. 回车\r与换行\n

    在计算机出现之前,有一种电传机械打字机,每秒可以打10个字符.但是有一个问题,就是打满一行后,需要进行换行,换行是需要0.2秒.如果这时有字符传入,就会丢失两个字符.为了解决这个问题,便定义了两个字符 ...

  6. 关于截取URL地址参数的方法

    JS获取URL中最后一个斜杠前面的内容 var url = window.location.href; var index = url.lastIndexOf("\/"); str ...

  7. 面试被问之-----sql优化中in与exists的区别

    曾经一次去面试,被问及in与exists的区别,记得当时是这么回答的:''in后面接子查询或者(xx,xx,xx,,,),exists后面需要一个true或者false的结果",当然这么说也 ...

  8. CentOS7攻克日记(四) —— 安装Mysql和Redis

    这一篇主要安装mysql,redis等数据库   在这篇开始之前,有一个坑,上一篇更改python软连接的时候,尽量都用名字是python3来软连接/usr/../bin/python3.6,把名字是 ...

  9. 关于在html中直接引入less文件遇到的小问题

    由于想直接在html页面上调用less文件,所以直接在代码上直接引入 <script src="bower_components/less/dist/less.js"> ...

  10. HDU 3466 Proud Merchants(背包问题,要好好理解)

    Problem Description Recently, iSea went to an ancient country. For such a long time, it was the most ...