api.js 1.13 KB
import axios from 'axios';
import config from 'config';

let axiosOptions = {
    baseURL: config.axiosBaseUrl,
    responseType: config.axiosResponseType,
    headers: {}
};

if (process.env.VUE_ENV !== 'server') {
    axiosOptions.headers['X-Requested-With'] = 'XMLHttpRequest';
}

const instanceAxios = axios.create(axiosOptions); // ssr不能使用全局的axios否则热更新会有问题

instanceAxios.interceptors.response.use(response => {
    return response;
}, error => {
    let msg = error && error.config ? `ssr api:[${error.config.method}] ${error.config.url} ${error.config.params || ''} ${error.response && error.response.data}` : 'axios error';

    return Promise.reject(msg);
});

export default {
    post(url, data, options) {
        return instanceAxios.post(url, data, options).then(res => res.data);
    },
    get(url, params) {
        return instanceAxios.get(url, {params}).then(res => res.data);
    },
    put(url, data, options) {
        return instanceAxios.put(url, data, options).then(res => res.data);
    },
    delete(url, params) {
        return instanceAxios.delete(url, {params}).then(res => res.data);
    }
};