import Vue from 'vue' import axios from 'axios' // import store from '~store' const service = axios.create({ withCredentials: true, baseUrl: '/' }) let reqCount = 0 // 请求计数器 service.interceptors.request.use(config => { // is server render, use ${baseUrl} directly rather than ${proxyUrl} config.url = config.url || '/' reqCount++ if (process.server) { if (config.url.indexOf('/inquiry') === 0) { config.url = process.env.commonUrl + config.url } else if (config.url.indexOf('/productsuer') === 0) { config.url = process.env.materialUrl + config.url } else if (config.url.indexOf('/messages') === 0) { config.url = process.env.messageUrl + config.url } else if (config.url.indexOf('/cmsApi') === 0) { config.url = process.env.cmsUrl + config.url } else if (config.url.indexOf('/sso') === 0) { config.url = process.env.ssoUrl + config.url } else { config.url = process.env.baseUrl + config.url } // let paramStr = '' // if (config.params) { // paramStr += '?' // for (let s in config.params) { // paramStr += s + '=' + config.params[s] + '&' // } // paramStr.substr(0, paramStr.length - 2) // } // console.log(config.url + paramStr) // config.headers.cookie = store.state.option.cookies + '; ' + store.state.option.sessionId // config.headers['User-Agent'] } else { document.getElementById('loading').setAttribute('class', 'loading in') } return config }, error => { return Promise.reject(error) }) service.interceptors.response.use(response => { // const cookie = response.headers['set-cookie'] // if (cookie && cookie.length) { // let cookies = cookie.split(';') // for (let i = 0; i < cookies.length; i++) { // let cookieArr = cookies[i].split('=') // if (cookieArr.length === 2 && cookieArr[0] === 'JSESSIONID') { // store.commit('option/SET_SESSION_ID', cookieArr[1]) // break // } // } // } // console.log('ccc', response.headers['set-cookie']) if (--reqCount <= 0 && !process.server) { document.getElementById('loading').setAttribute('class', 'loading') } return response }, error => { if (!process.server) { if (--reqCount <= 0) { document.getElementById('loading').setAttribute('class', 'loading') } // 401拦截 if (error.response.status === 401 && // 当前账套店铺信息 !/\/store-service\/stores$/g.test(error.response.config.url) && // 店铺关注 !/\/trade\/storeFocus\/ifFocus/g.test(error.response.config.url) && // 器件收藏 !/\/trade\/collection\/list/g.test(error.response.config.url)) { window.location.href = `/auth/login?returnUrl=${window.location.href}` return } } return Promise.reject(error) }) Vue.prototype.$http = service export default service