vue项目
引入axios
import axios from 'axios'
创建axios
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000,
headers: {
"Content-Type": "application/json;charset=utf-8"
})
请求拦截
service.interceptors.request.use(
config => {
config.headers = config.headers || {}
if (localStorage.getItem('token')) {
config.headers.token= localStorage.getItem('token') || ''
}
return config
},
error => {
console.log(error)
return Promise.reject(error)
}
)
****响应拦截
service.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 200) {
if (error.response.status == 401) {
localStorage.removeItem("token");
setTimeout(()=> {
window.location.reload()
}, 500)
return Promise.reject(res.messge)
}
return Promise.reject(error.response.data || 'Error')
} else {
return res
}
},
error => {
// elementui 组件
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
标签:axios,return,service,error,封装,config,response From: https://www.cnblogs.com/mdtayz/p/16784296.html