直接放代码api.js
import axios from "axios";
import {Message} from 'element-ui';
import router from "@/router";
//响应拦截器
axios.interceptors.response.use(
(success) => {
//成功获取连接,但是业务逻辑可能存在错误
if (success.status && success.status == 200) {
//success.data是拿到后端传过来的数据对象包括{code,message,obj},
if (success.data.code == 500 || success.data.code == 401 || success.data.code == 403) {
//连接成功,但是出现错误
Message.error({message: success.data.message});
return;
}
if (success.data.code == 200) {
Message.success({message: success.data.message})
}
}
//拦截器过了之后需要放行,将数据返回。
return success.data;
},
(error) => {
//与后端连接失败
if (error.response.data == 404 || error.response.data == 501 || error.response.data == 503) {
Message.error({message: '页面被吃了!'});
} else if (error.response.data == 403) {
Message.error({message: '权限不足,请联系管理员!'});
} else if (error.response.data == 401) {
Message.error({message: '尚未登录,请登录!'});
//顺便送客户回首页
router.replace("/")
} else {
if (error.response.data) {
Message.error({message: error.response.data});
} else {
Message.error({message: '未知错误'});
}
}
return;
});
//防止业务需求需要修改请求地址
let baseUrl = '';
//传送json格式的post请求
export const postRequest = (url, params) => {
return axios({
method: 'post',
url: `${baseUrl}${url}`,
data: params
});
}
//传送json的get请求
export const getRequest = (url, params) => {
return axios({
method: 'get',
url: `${baseUrl}${url}`,
data: params
});
}
//传送的json的delete请求
export const deleteRequest = (url, params) => {
return axios({
method: 'delete',
url: `${baseUrl}${url}`,
data: params
});
}
//传送json的put请求
export const putRequest = (url, params) => {
return axios({
method: 'put',
url: `${baseUrl}${url}`,
data: params
});
}
网友评论