vue-axios配置

在Vue项目中,如果没有引入JQuery,那么使用axios来做http请求将是一个不错的选择,因为它相对于ajax不需要引入JQuery包,这样项目就会小很多。

先引入axios依赖包

$ yarn add axios vue-axios

下面,我们来看一下axios的常用基本配置

导入axios,一般我们会在一个公共方法js文件里做一下操作,它通常被命名为util.js

import axios from 'axios'

// 全局设置超时时间
axios.defaults.timeout = 20000

// 请求路由拦截 一般在此处配置请求头和token
axios.interceptors.request.use(function (config) {
    let token = sessionStorage.getItem("user_token");
    if (config.method == 'get') {
        config.headers = {
            'Content-Type': 'application/json',
            'Authorization': token
        }
        config.data = true
    } else {
        config.headers = {
            'Content-Type': 'application/json',
            'Authorization': token
        }
    }
    return config
}, function (error) {
    return Promise.reject(error)
})

// respone拦截器 响应路由拦截 一般在此处做返回错误码的后续操作,比如没有权限跳回登录页
axios.interceptors.response.use(
    response => {
        const res = response.data
        return response
    },
    error => {
        if (error.response.status == 401) { // 没有权限
            Message({
                message: '登录过期,请重新登录!',
                type: 'error'
            })
            window.location.href = '/#/login'
        }
        if (error.response.status == 403) { // 被拒绝访问
            Message({
                message: '您没有此操作的权限!',
                type: 'error'
            })
            window.location.href = '/#/error?code=' + 403
        }
        if (error.response.status == 502) { // 服务器错误
            Message({
                message: '服务器正在发布中,请稍后重试!',
                type: 'error'
            })
            window.location.href = '/#/login'
        }
        return Promise.reject(error)
    }
)

axios.defaults.headers.delete['Content-Type'] = 'application/x-www-form-urlencoded' // 单独配置delete的请求头

// 以下是几种常用的公共方法
var instance = axios.create({
    headers: { 'content-type': 'multipart/form-data' }
});

export default {
    Get(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.get(url, {
                params
            }).then(res => {
                resolve(res.data)
            }).catch(err => {
                reject(err.data)
            })
        })
    },
    Getfile(url, params = {}, name) {
        return new Promise((resolve, reject) => {
            axios.get(url, {
                params,
                responseType: 'blob'
            }).then(res => {
                resolve(res.data)
                let blob = new Blob([res.data], {
                    type: 'application/vnd.ms-excel'
                })
                // 先转码再解码
                let fileName
                // let fileName = decodeURI(escape(res.headers['content-disposition'].split('filename=')[1]))
                if (name && name != '' && name != null) {
                    fileName = name
                } else {
                    fileName = decodeURI(res.headers['content-disposition'].split('filename=')[1])
                }
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, fileName)
                } else {
                    var link = document.createElement('a')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = fileName
                    link.click()
                    Message({
                        message: '下载成功!',
                        type: 'success'
                    })
                    //释放内存
                    window.URL.revokeObjectURL(link.href)
                }
            }).catch(err => {
                console.log('err', err)
                if (err) {
                    Message({
                        message: '下载失败!',
                        type: 'error'
                    })
                }
                reject(err.data)
            })
        })
    },
    Postfile(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url,
                params,
                { responseType: 'blob' }
            ).then(res => {
                resolve(res.data)
                let blob = new Blob([res.data], {
                    type: 'application/vnd.ms-excel'
                })
                // 先转码再解码
                // let fileName = decodeURI(escape(res.headers['content-disposition'].split('filename=')[1]))
                let fileName = decodeURI(res.headers['content-disposition'].split('filename=')[1])
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, fileName)
                } else {
                    var link = document.createElement('a')
                    link.href = window.URL.createObjectURL(blob)
                    link.download = fileName
                    link.click()
                    Message({
                        message: '下载成功!',
                        type: 'success'
                    })
                    //释放内存
                    window.URL.revokeObjectURL(link.href)
                }
            }).catch(err => {
                if (err) {
                    Message({
                        message: '下载失败!',
                        type: 'error'
                    })
                }
                reject(err.data)
            })
        })
    },
    Post(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, params)
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err.data)
                })
        })
    },
    Postform(url, data = {}) {
        return new Promise((resolve, reject) => {
            instance.post(url, data)
                .then(res => {
                    resolve(res.data);
                }, err => {
                    reject(err.data)
                })
        })
    },
    Put(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.put(url, params)
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err.data)
                })
        })
    },
    Delete(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.delete(url, data)
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err.data)
                })
        })
    },
}

  

 

posted @ 2020-09-08 11:48  心心眼  阅读(539)  评论(0编辑  收藏  举报