axios.js 1.4 KB
Newer Older
yma16's avatar
yma16 已提交
1
'use strict'
yma16's avatar
yma16 已提交
2

yma16's avatar
yma16 已提交
3 4
import Vue from 'vue'
import axios from 'axios'
yma16's avatar
yma16 已提交
5 6 7 8 9 10 11

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
yma16's avatar
yma16 已提交
12 13 14
    // baseURL: process.env.baseURL || process.env.apiUrl || ""
    // timeout: 60 * 1000, // Timeout
    // withCredentials: true, // Check cross-site Access-Control
yma16's avatar
yma16 已提交
15
}
yma16's avatar
yma16 已提交
16

yma16's avatar
yma16 已提交
17
const _axios = axios.create(config)
yma16's avatar
yma16 已提交
18 19

_axios.interceptors.request.use(
yma16's avatar
yma16 已提交
20
    function (config) {
yma16's avatar
yma16 已提交
21
    // Do something before request is sent
yma16's avatar
yma16 已提交
22 23 24
        return config
    },
    function (error) {
yma16's avatar
yma16 已提交
25
    // Do something with request error
yma16's avatar
yma16 已提交
26 27
        return Promise.reject(error)
    }
yma16's avatar
yma16 已提交
28
)
yma16's avatar
yma16 已提交
29 30 31

// Add a response interceptor
_axios.interceptors.response.use(
yma16's avatar
yma16 已提交
32
    function (response) {
yma16's avatar
yma16 已提交
33
    // Do something with response data
yma16's avatar
yma16 已提交
34 35 36
        return response
    },
    function (error) {
yma16's avatar
yma16 已提交
37
    // Do something with response error
yma16's avatar
yma16 已提交
38 39
        return Promise.reject(error)
    }
yma16's avatar
yma16 已提交
40
)
yma16's avatar
yma16 已提交
41

yma16's avatar
yma16 已提交
42
Plugin.install = function (Vue, options) {
yma16's avatar
yma16 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56
    Vue.axios = _axios
    window.axios = _axios
    Object.defineProperties(Vue.prototype, {
        axios: {
            get () {
                return _axios
            }
        },
        $axios: {
            get () {
                return _axios
            }
        }
    })
yma16's avatar
yma16 已提交
57
}
yma16's avatar
yma16 已提交
58 59 60

Vue.use(Plugin)

yma16's avatar
yma16 已提交
61
export default Plugin