vue项目中axios拦截器配置及不同接口对应不同后端接口域名配置
- 一、axios基础配置
- 二、不同接口对应不同后端接口域名配置
一、axios基础配置
import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
const service = axios.create({timeout: 5000,withCredentials: false,
})
service.interceptors.request.use(config => {if (config.isCustomHeader) {config.headers['FLAGINFO-CLIENTID'] = 'WEB:DC'}if (store.state.token) {if (config.isCustomHeader) {config.headers['FLAGINFO-SSO-TOKEN'] = store.state.token} else {config.headers['token'] = store.state.token}} config.url = process.env.VUE_APP_WEB_API + config.url if (config.params) {config.params.f_rnd = new Date().getTime()} else {config.params = {f_rnd: new Date().getTime(),}}return config},error => {return Promise.reject(error)}
)
service.interceptors.response.use(({ data }) => {if (data.code && data.code !== 200) {Message({showClose: true,message: data.message || data.msg,duration: 2000,type: 'error',})return Promise.reject(data)}return data},error => {console.log('error:' + error) return Promise.reject(error)}
)
export default service
二、不同接口对应不同后端接口域名配置
export function login(data) {return request({url: '/soo/loginUrl',method: 'post',data: data,isUserCenter: true,})
}
export function trueUser(phone) {return request({url: `/loginGet/checkUserPhone/${phone} `,method: 'get',})
}
if (config.isUserCenter) {config.url = process.env.API_USER_CENTER + config.url
} else {config.url = process.env.API_SERVER + config.url
}