Some notes on using axios in Vue

1. Basic use

  • Now our team basically uses axios to initiate requests, the way to use it is as follows
  • Return promise object in service.js file
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)
                })
        })
    },
}
  • Call the method in the component, use the async await statement, and add try catch to the outer layer to catch exceptions
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. Custom request headers

  • In the development process, all our requests now have to go through the gateway, and the gateway needs to pass userId and token for authentication. If we have to write in each request, it will be very troublesome. At this time, we need to use axios interceptor
  • Create the folder structure as shown

  • Code
/*
 * 在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
  • Custom request header problem
    • There is a problem with the custom request header, userId, token, these parameters are not the default attributes in the http request header, so the browser will first initiate an option pre-request to the back-end service, and when the server responds, it can be added in the request header. When these custom attributes are used, the browser will initiate a real get or post data request
    • So at this time, the backend needs to set the cross-domain to *, otherwise it will report cross-domain problems

3. Use interceptors to uniformly handle error messages

  • We can use the interceptor of axios to do unified error status code processing
    • For example, 401 status code jumps to the login page
    • Jumps such as token expiration check
  • Code
/*
 * 新建一个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. References and citations

5. Special thanks

  • company's partners

6. Disclaimer

  • Some of the content in this document is taken from many blogs on the Internet, and is only used as a supplement and arrangement of my own knowledge, and is shared with other coders in need, and will not be used for commercial use.
  • Because the addresses of many blogs are not saved in time after reading, many of them will not indicate the source here. Thank you very much for your sharing, and I hope everyone understands.
  • If the original author feels uncomfortable, you can contact me in time at [email protected], and I will delete the content of the dispute in time

7. Statement of Accountability

  • If there is a large paragraph that quotes more than 50% of the full text, please indicate the source of the original text at the end of the document: Longma Xingkong - Shi Guoqing - Jupiter - https://my.oschina.net/u/1416844/blog , otherwise it will be regarded as For plagiarism, legal investigation, please respect your personal intellectual property rights.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324539505&siteId=291194637