1、创建request.js
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000
})
// request interceptor
service.interceptors.request.use(
config => {
if (store.getters.token) {
config.headers['token'] = getToken()
}
return config
},
error => {
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (res.code != 200) {
console.log(res)
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
/*if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}*/
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
2、在api文件下创建js对接口进行二次封装
import request from '@/utils/request'//导入上面的requset.js
export function getAllMessageInfo(pages) {
return request({
url: '/messageInfo/getAllMessageInfo',
method: 'post',
data: pages
})
}
3、在组件vue文件上对于自己写的方法进行调用
<script>
import {getAllMessageInfo} from "@/api/messageInfo/messageInfo"//导入方法
okgetAllMessageInfo() {
const pages={}
pages.current=this.current
pages.size=this.size
getAllMessageInfo(pages).then(response=>{
console.log(response)//这里可以做自己想做的事情
})
},
</script>
|