代码附加在最后,主要是函数axiosInit.
如下图, 为什么打印的日志不是:
xxx5555
xxxxx---0
而是:
xxxxx---1 request.js:56
xxxxx---0 request.js:49
Uncaught TypeError: window._app is undefined
getBaseUrl request.js:9
init request.js:16
axiosInit request.js:50
axiosRequest request.js:57
....
目的:
在main.js最后上报一条日志
// request.js
import axios from 'axios';
let axiosInited = false;
let service;
function init () {
function getBaseUrl () {
if (process.env.NODE_ENV === 'development') {
return window._app.$store.state.vuex_host_dev;
} else {
return window._app.$store.state.vuex_host_prod;
}
}
service = axios.create({
baseURL: getBaseUrl(),
timeout: 5000,
});
service.interceptors.request.use(
(config) => {
if (!config.headers) config.headers = {};
config.headers.token = window._app.$store.state.vuex_token;
config.headers['Content-Type'] = 'application/json;charset=utf-8';
return config;
},
(error) => {
console.log(error);
return Promise.reject();
}
);
service.interceptors.response.use(
(response) => {
if (response.status === 200) {
return response.data;
} else {
Promise.reject();
}
},
(error) => {
console.log(error);
return Promise.reject();
}
);
}
export const axiosInit = function () {
console.log('xxxxx---0');
init();
axiosInited = true;
};
export const axiosRequest = function () {
if (!axiosInited) {
console.log('xxxxx---1');
axiosInit();
}
console.log('xxxxx---2');
return service;
};
// export default service;
//index.js
import { axiosRequest } from '../plugins/request';
const request = axiosRequest();
export const httpGet = (url, query, headers) => {
return request({
url: url,
method: 'get',
params: query,
headers: headers,
});
};
export const logOpened = (query) => {
console.log('request', request);
return httpGet('/xxx', query);
};