import axios from "axios";
import qs from "qs";
import { Toast } from "antd-mobile";
/****** 创建axios实例 ******/
const service = axios.create({
baseURL: "http://localhost:8080", // api的base_url
timeout: 5000, // 请求超时时间
});
service.interceptors.request.use(
(config) => {
// loading 加载开始
console.log("数据加载中");
config.method === "post"
? (config.data = qs.stringify({ ...config.data }))
: (config.params = { ...config.params });
config.headers["Content-Type"] = "application/x-www-form-urlencoded";
return config;
},
(error) => {
//请求错误处理
console.log("warn");
Promise.reject(error);
}
);
/****** respone拦截器==>对响应做处理 ******/
service.interceptors.response.use(
(response) => {
console.log(response);
//这里根据后端提供的数据进行对应的处理
if (response.data.status === 200) {
// loading加载结束
return response;
} else {
console.log("响应失败");
}
},
(error) => {
const { response } = error;
//响应错误处理
console.log(response, "错误信息");
let text = response.data.status === 404 ? "404" : "网络异常,请重试";
console.log("失败");
return Promise.reject(error);
}
);
export default service;
axios二次封装
最新推荐文章于 2022-12-03 23:39:11 发布