/src/utils/request.js
import axios from 'axios'
import {Loading, Toast, Dialog, Notify} from 'vant'
import router from '@/router'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
// axios中请求配置有baseURL选项,表示请求URL公共部分
baseURL: '/',
// 超时
timeout: 10000
})
// request拦截器
service.interceptors.request.use(
config => {
let hds = config.headers;
let token = localStorage.getItem('refreshToken');
if (token) {
hds.Authorization = token;
}
config.headers = hds;
return config
},
error => {
console.log(error)
Promise.reject(error)
}
)
let DialogShow = false;
// 响应拦截器
service.interceptors.response.use(res => {
if (typeof res.data == "string") {
document.write(res.data)
}
const code = res.data.code;
if (code === 401) {
//无权限、token过期
if (!DialogShow) {
DialogShow = true;
Dialog.confirm({
title: '系统提示',
message: '登录状态已过期,您可以继续留在该页面,或者重新登录',
})
.then(() => {
localStorage.removeItem('refreshToken');
// token 过期
router.replace({ path: '/login' })
})
.catch(() => {
// on cancel
});
}
} else if (code !== 200) {
//请求出错
Notify({type: 'danger', message: res.data.message ? res.data.message : '请求出错了!'});
return Promise.reject('error')
} else {
//成功回调
DialogShow = false;
return res.data
}
},
error => {
console.log('err' + error)
Toast.fail(error.message);
return Promise.reject(error)
}
)
export default service
使用:
<template>
<div class="hello">
{{msg}}
</div>
</template>
<script>
import request from '@/utils/request.js'
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods:{
getMsg() {
let filters = {
pageNum:0
}
request({
method: 'post',
url: '/mdm/hotel/selectMdmHotelList',
data: filters
}).then((response)=> {
}).catch((error)=> {
});
},
},
mounted() {
this.getMsg()
}
}
</script>
<style lang="less" scoped>
</style>