import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
let baseURL
let wsBaseURL
if (process.env.NODE_ENV === 'development') {
baseURL = ''
} else {
baseURL = `${window.location.protocol}//${window.location.hostname}:${window.location.port}`
}
const service = axios.create({
baseURL: baseURL,
timeout: 10000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
config.headers['token'] = store.state.user.token
if (config.method.toUpperCase() === 'POST') {
if (!config.data) {
config.data = {}
}
//接口默认要传的字段,请求每次都会带上
/** **/ const xxx = store.state.xxx || ''
/** **/ if (!config.data.xxx && xxx) {
/** **/ config.data.xxx = xxx
}
}
return config
},
error => {
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
async response => {
const res = response.data || {}
// if the custom code is not 20000, it is judged as an error.
if (res.code === 200 ) {
return res
} else if (res.code === 约定的值) {
// Token 校验失败
await store.dispatch('user/logout')
} else if (res.code === 约定的值) {
Message({
message: res.msg || '系统错误,请稍后重试',
type: 'error',
duration: 3000
})
} else {
if (!res.msg) {
res.msg = '系统错误,请稍后重试'
}
res.message = res.msg
return Promise.reject(res)
}
},
error => {
console.log(error)
let msg
if (error && error.response) {
msg = error.response.data.msg
}
msg = msg || '系统错误,请稍后重试'
return Promise.reject({ code: -100, msg, message: msg })
}
)
export { baseURL }
export default service
vue request封装
最新推荐文章于 2024-09-20 15:39:10 发布