vue axios 接口封装
import axios from 'axios'
// axios基本配置
axios.defaults.timeout = 5000
axios.defaults.baseURL = 'http://192.168.1.8:8500'
axios.defaults.withCredentials = false
// http request 拦截器
axios.interceptors.request.use(
config => {
const sid = localStorage.getItem('user_info') ? JSON.parse(localStorage.getItem('user_info')).sessionid : ''
if (sid) {
config.headers.sid = sid
}
return config
},
err => {
return Promise.reject(err)
}
)
// http response 拦截器
axios.interceptors.response.use(
response => {
switch (response.data.code) {
case 1:
return response.data;
case "200":
return response.data;
case 100:
window.vm.$message({
message:'请先登录',
type:'error',
onClose:function(){
window.router.push('/login');
setTimeout(() => {
window.router.go(0)
}, 300)
}
});
case 101:
window.vm.$message({
message:'登录失效',
type:'error',
onClose:function(){
window.router.push('/login')
setTimeout(() => {
window.router.go(0)
}, 300)
}
});
//清空localStorage
localStorage.removeItem('user_info');
default:
console.log(response.data.msg)
}
},
error => {
return Promise.reject(error)
})
/**
- post 请求方法
- @param url
- @param data
- @returns {Promise}
*/
export function post (url, data) {
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(response => {
resolve(response)
}, err => {
reject(err)
})
})
}
/**
- get 请求方法
- @param url
- @param data
- @returns {Promise}
*/
export function get (url, data) {
return new Promise((resolve, reject) => {
axios.get(url, data)
.then(response => {
resolve(response)
}, err => {
reject(err)
})
})
}
/**
- put 请求方法
- @param url
- @param id
- @param data
- @returns {Promise}
*/
export function put (url, id, data) {
return new Promise((resolve, reject) => {
axios.put(url + id, data)
.then(response => {
resolve(response)
}, err => {
reject(err)
})
})
}
/**
- delete 请求方法
- @param url
- @param id
- @returns {Promise}
*/
export function _delete (url, id) {
return new Promise((resolve, reject) => {
axios.delete(url + id)
.then(response => {
resolve(response)
}, err => {
reject(err)
})
})
}
export default axios