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的拦截器
- 创建如图所示的文件夹结构
import '@/utils/request/request.js'
import config from '@/config/index.js'
if (config.setting.customHttpHeader) {
require('@/utils/request/header.js')
}
import globalConfig from '@/config/index.js'
import storage from '@/utils/storage.js'
import axios from 'axios'
let func = function (config) {
if (globalConfig.setting.permission) {
if (storage.getItem('SGQ.global.userAuthor') != null) {
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.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过期校验等跳转
- 代码实现
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:
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. 追责声明
原文发布时间为:2017/12/07
原文作者:
龙马行空
本文来源:
开源中国 如需转载请联系原作者