Vue中使用axios的一些注意点


声明:本文转载自https://my.oschina.net/u/1416844/blog/1586631,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

1. 基本使用

  • 现在我们的团队使用的基本都是axios发起请求,使用方式如下
  • 在service.js文件中返回promise对象
import config from '@/config' import axios from 'axios' export default{     /*启用停用*/     setB2bStoreGoodsBlackUpOrDown(data) {         return new Promise(function (resolve, reject) {             const url = `${config.server.http}${config.server.host}/b2b-seller-admin/setStoreGoodsBlackUpOrDown`             axios.post(url, data)                 .then(function (data) {                     resolve(data)                 })                 .catch(function (error) {                     reject(error)                 })         })     },     /*一个接口查黑名单*/     getListB2bCanaleStoreGoodsBlacks(data) {         return new Promise(function (resolve, reject) {             const url = `${config.server.http}${config.server.host}/b2b-seller-admin/page/getListCanaleStoreGoodsBlacks`             axios.post(url, data)                 .then(function (data) {                     resolve(data)                 })                 .catch(function (error) {                     reject(error)                 })         })     }, } 
  • 在组件中调用方法,使用async await语句,外层加try catch 捕获异常
import advService from '@B2B/services/substatAdmin/advService.js' import scrollMixins from '@/mixins/scrollMixins.js' import config from '@/config' import storage from '@/utils/storage.js'  export default {     mixins: [scrollMixins],     data() {         return {             con1:false,             con10:false,             locationoptions: [],             B2bAdv: {                 siteid: null,                 sort: 0,                 picUrl: "",                 openTpye: 0             }         }     },     methods: {         async saveAdv(){             let flag = this.Formrule()             if (flag) {                 try {                     this.B2bAdv.startTime = this.B2bAdv.timevalue[0].getTime().toString().substr(0, 13)                     this.B2bAdv.endTime = this.B2bAdv.timevalue[1].getTime().toString().substr(0, 13)                     const data = await advService.addB2bAdv(this.B2bAdv)                     if (data.status == 200 && data.data.result) {                         this.closeTab()                      } else {                         console.log(data.status.statusReason)                         this.$customMessage("新增失败", "error")                     }                 }                 catch (e) {                     this.$customMessage("新增失败", "error")                     console.log(e)                 }              }         }     } } 

2. 自定义请求头

  • 在开发过程中,我们所有的请求现在都要走网关,而且网关需要传递userId和token做鉴权,如果在每个请求中都要写,那么会很麻烦,这个时候我们需要使用axios的拦截器
  • 创建如图所示的文件夹结构

  • 代码实现
/*  * 在main.js的入口文件引入request.js  * */  /***全局配置配置***/ // axios请求配置 import '@/utils/request/request.js' 
/*  * request.js  * */  /*  * @Author: 石国庆  * @Desc: 所有axios的拦截器,默认配置都可以写在这里  * @Date: 2017.11.14  * */  import config from '@/config/index.js' // 开关控制 if (config.setting.customHttpHeader) {     // 这里面没法用import     // 添加用户id的请求头     require('@/utils/request/header.js')     // import '@/utils/request/header.js' } 
/*  * header.js  * */  /*  * @Author: 石国庆  * @Desc: axios的请求头,用于添加网关需要的userId和token自定义请求头  * @Date: 2017.11.14  * */ import globalConfig from '@/config/index.js' import storage from '@/utils/storage.js' import axios from 'axios'   // 这点的重点就是不能写死,还要把这个方法导出去,因为还要兼容用ajax写的老代码 let func = function (config) {     // 开关控制     if (globalConfig.setting.permission) {         if (storage.getItem('SGQ.global.userAuthor') != null) {             // 这里的config包含每次请求的内容             config.headers.userId = storage.getItem('SGQ.global.userAuthor').id             config.headers.token = storage.getItem('SGQ.global.userAuthor').token             config.headers.userName = storage.getItem('SGQ.global.userAuthor').userName             config.headers.orgId = storage.getItem('SGQ.global.userAuthor').orgId         }     } else {         // 这里的config包含每次请求的内容         config.headers.userId = '2167676703289898'         config.headers.token = 'eyJhbGciOiJIUzUxMiJ9.eyJrtrtriOiIyMTYwMDMyIiwiaWF0IjoxNTA5MTYwOTIzfQ.Gz6eKAkimLg7777777777777777777777777ZZF2KiX01ux7OVphfGmUT6o9q-n5eJxN0RA99evCHpfyR78gbVg'         config.headers.userName = 'cj'         config.headers.orgId = 1     }     return config }   // 使用请求的拦截器 axios.interceptors.request.use(func, function (err) {     return err })  export default func 
  • 自定义请求头问题
    • 自定义请求头遇到了一个问题,userId,token,这些参数都不是http请求头中默认的属性,所以浏览器会先向后端服务发起一个option的预请求,当服务器响应在请求头中可以加这些自定义属性的时候,浏览器才会发起真实的get或者post数据请求
    • 所以这个时候后端需要把跨域都设置为*,否则会报跨域问题

3. 用拦截器统一处理错误信息

  • 我们可以利用axios的拦截器,做统一的错误状态码处理
    • 比如401状态码跳转登录页
    • token过期校验等跳转
  • 代码实现
/*  * 新建一个error.js,然后在request.js文件中引入  * */  /*  * @Author: 石国庆  * @Desc: axios的请求头,用于添加网关需要的userId和token自定义请求头  * @Date: 2017.11.14  * */ import globalConfig from '@/config/index.js' import storage from '@/utils/storage.js' import axios from 'axios'  let errFunc=function (error) {     if (error.response) {         switch (error.response.status) {             case 401:                 // 返回 401 清除token信息并跳转到登录页面                 router.replace({                     path: 'login',                     query: {redirect: router.currentRoute.fullPath}                 })         }     }     // 返回接口返回的错误信息     return error.response.data }   // 使用请求的拦截器 axios.interceptors.response.use(function (response) {     return response },errFunc)  export default errFfunc 

4. 参考和引用

5. 特别感谢

  • 公司的小伙伴

6. 免责说明

  • 本文档中的部分内容摘自网上的众多博客,仅作为自己知识的补充和整理,并分享给其他需要的coder,不会用于商用。
  • 因为很多博客的地址看完没有及时做保存,所以很多不会在这里标明出处,非常感谢各位大牛的分享,也希望大家理解。
  • 如果原文作者感觉不适,可以及时联系我shiguoqing999@163.com,我将及时删除争议部分内容

7. 追责声明

  • 如有大段引用超过全文50%的内容,请在文档结尾标明原文出处:龙马行空-石国庆-朱庇特-https://my.oschina.net/u/1416844/blog,否则将视为抄袭,予以法律追究,请各位尊重个人知识产权。

本文发表于2017年12月08日 08:33
(c)注:本文转载自https://my.oschina.net/u/1416844/blog/1586631,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 2989 讨论 0 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1