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