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. 追责声明