侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Vue中axios的封装(报错、鉴权、跳转、拦截、提示)

前端  /  管理员 发布于 4年前   644

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

实现的功能

  • 统一捕获接口报错 : 用的axios内置的拦截器
  • 弹窗提示: 引入 Element UI 的 Message 组件
  • 报错重定向: 路由钩子
  • 基础鉴权: 服务端过期时间戳和token,还有借助路由的钩子
  • 表单序列化: 我这边直接用 qs (npm模块),你有时间也可以自己写

用法及封装

用法

// 服务层 , 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: 10000, responseType: "json", withCredentials: true, // 是否允许带cookie这些 headers: {  "Content-Type": "application/x-www-form-urlencoded;" }});//POST传参序列化(添加请求拦截器)Axios.interceptors.request.use( config => {  // 在发送请求之前做某件事  if (   config.method === "post"  ) {   // 序列化   config.data = qs.stringify(config.data);   // 温馨提示,若是贵公司的提交能直接接受json 格式,可以不用 qs 来序列化的  }  // 若是有做鉴权token , 就给头部带上token  // 若是需要跨站点,存放到 cookie 会好一点,限制也没那么多,有些浏览环境限制了 localstorage 的使用  // 这里localStorage一般是请求成功后我们自行写入到本地的,因为你放在vuex刷新就没了  // 一些必要的数据写入本地,优先从本地读取  if (localStorage.token) {   config.headers.Authorization = localStorage.token;  }  return config; }, error => {  // error 的回调信息,看贵公司的定义  Message({   // 饿了么的消息弹窗组件,类似toast   showClose: true,   message: error && error.data.error.message,   type: 'error'  });  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 *    1000;   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 === 403) {     router.push({      path: "/error/403"     });    }    if (error.response.status === 500) {     router.push({      path: "/error/500"     });    }    if (error.response.status === 502) {     router.push({      path: "/error/502"     });    }    if (error.response.status === 404) {     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 *    1000;   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: 12 }, // 查询对象序列化函数 paramsSerializer: function(params) {}, // request body data: { key: "aa" }, // 超时设置s timeout: 1000, // 跨域是否带Token withCredentials: false, // 自定义请求处理 adapter: function(resolve, reject, config) {}, // 身份验证信息 auth: { uname: "", pwd: "12" }, // 响应的数据格式 json / blob /document /arraybuffer / text / stream responseType: "json", // xsrf 设置 xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", // 下传和下载进度回调 onUploadProgress: function(progressEvent) {  Math.round(progressEvent.loaded * 100 / progressEvent.total); }, onDownloadProgress: function(progressEvent) {}, // 最多转发数,用于node.js maxRedirects: 5, // 最大响应数据大小 maxContentLength: 2000, // 自定义错误状态码范围 validateStatus: function(status) {  return status >= 200 && status < 300; }, // 用于node.js httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 用于设置跨域请求代理 proxy: {  host: "127.0.0.1",  port: 8080,  auth: {   username: "aa",   password: "2123"  } }, // 用于取消请求 cancelToken: new CancelToken(function(cancel) {})};

总结

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

鉴权需要再严谨一些,比如token 可以遵循 JWT 的规格,以及引入中间层nodejs(对传输的做拦截封装加解密,聚合接口);

以上所述是小编给大家介绍的Vue中axios的封装(报错、鉴权、跳转、拦截、提示),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

您可能感兴趣的文章:

  • vue中Axios的封装与API接口的管理详解
  • 详解vue axios二次封装
  • 详解vue中axios的封装
  • vue中axios的封装问题(简易版拦截,get,post)
  • Vue二次封装axios为插件使用详解
  • 详解给Vue2路由导航钩子和axios拦截器做个封装
  • vue 里面使用axios 和封装的示例代码


  • 上一条:
    Vue formData实现图片上传
    下一条:
    vue element 生成无线级左侧菜单的实现代码
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 使用 Alpine.js 排序插件对元素进行排序(0个评论)
    • 在js中使用jszip + file-saver实现批量下载OSS文件功能示例(0个评论)
    • 在vue中实现父页面按钮显示子组件中的el-dialog效果(0个评论)
    • 使用mock-server实现模拟接口对接流程步骤(0个评论)
    • vue项目打包程序实现把项目打包成一个exe可执行程序(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-03
    • 2018-04
    • 2018-05
    • 2018-06
    • 2018-09
    • 2018-11
    • 2018-12
    • 2019-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客