美文网首页
axios封装

axios封装

作者: 寒梁沐月 | 来源:发表于2018-10-08 15:37 被阅读13次
    import axios from 'axios';
    import Qs from 'qs'
    import {
        Message
    } from 'element-ui'
    const service = axios.create({
        baseURL: '/api',
        timeout: 0,
        validateStatus: function (status) {
            return status >= 200 && status < 300;
        }
    })
    service.defaults.headers = {
        'X-Requested-With': 'XMLHttpRequest',
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    };
    service.interceptors.request.use(config => {
        if (config.method.toLocaleLowerCase() === 'post' 
             || config.method.toLocaleLowerCase() === 'put' 
             || config.method.toLocaleLowerCase() === 'delete') {
               config.data = qs.stringify(config.data)
         }
        if (config.url.indexOf('?') >= 0) {
            config.url += ('&_t=' + new Date().getTime());
        } else {
            config.url += '?_t=' + new Date().getTime();
        }
        return config
    }, error => {
        Promise.reject(error)
    })
    service.interceptors.response.use(
        response => {
            return response.data;
        },
        error => {
            console.log('err' + error)
            Message({
                message: error.message,
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(error)
        })
    export default service
    

    相关文章

      网友评论

          本文标题:axios封装

          本文链接:https://www.haomeiwen.com/subject/wtljaftx.html