axios封装

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封装)