Vue中使用axios的一些注意点

简介:

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的拦截器
  • 创建如图所示的文件夹结构
b26956622480bb97846f0c775e95245bf3266ec3
  • 代码实现
/*
 * 在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/07
原文作者: 龙马行空
本文来源: 开源中国 如需转载请联系原作者

目录
相关文章
|
9天前
|
JSON 前端开发 JavaScript
3分钟让你学会axios在vue项目中的基本用法(建议收藏)
3分钟让你学会axios在vue项目中的基本用法(建议收藏)
41 0
|
2月前
|
XML JavaScript 前端开发
axios如何在vue中使用
axios如何在vue中使用
27 1
|
28天前
|
Web App开发 前端开发 JavaScript
Spring Boot整合 mybatisplus(后端) Vue+echarts+Element UI+axios(前端)---前后端项目实例demo
Spring Boot整合 mybatisplus(后端) Vue+echarts+Element UI+axios(前端)---前后端项目实例demo
21 1
|
29天前
|
前端开发 JavaScript Java
springboot+mybatis plus+vue+elementui+axios 表格分页查询demo
springboot+mybatis plus+vue+elementui+axios 表格分页查询demo
32 0
|
1月前
|
资源调度 JavaScript 前端开发
QGS
|
3月前
|
JavaScript 安全 前端开发
手摸手vue2+Element-ui整合Axios
手摸手vue2+Element-ui整合Axios
QGS
28 0
|
3月前
Vue3 配置代理和使用全局axios请求数据
Vue3 配置代理和使用全局axios请求数据
74 1
|
3月前
|
前端开发 JavaScript 算法
springboot+vue+mybatis-plus+axios实现商品的CRUD
springboot+vue+mybatis-plus+axios实现商品的CRUD
35 0
|
3月前
|
JavaScript
Vue如何请求接口——axios请求
Vue如何请求接口——axios请求
30 0
|
JavaScript 前端开发 API
VUE axios使用方法与跨域问题解决
'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
21063 0