75 lines
1.7 KiB
JavaScript
75 lines
1.7 KiB
JavaScript
import axios from "axios";
|
|
import config from "../config/config";
|
|
import axiosAdapterUniapp from "axios-adapter-uniapp";
|
|
import $store from "../store/index";
|
|
|
|
const service = axios.create({
|
|
baseURL: config.baseApi, // url = base url + request url
|
|
headers: {
|
|
"X-Requested-With": "XMLHttpRequest",
|
|
"Content-Type": "application/json-patch+json",
|
|
},
|
|
adapter: axiosAdapterUniapp,
|
|
timeout: 5000, // request timeout
|
|
});
|
|
|
|
// request interceptor
|
|
service.interceptors.request.use(
|
|
(config) => {
|
|
if (uni.getStorageSync("ukey")) {
|
|
config.headers["Authorization"] = "Bearer " + uni.getStorageSync("ukey");
|
|
}
|
|
|
|
return config;
|
|
},
|
|
(error) => {
|
|
// do something with request error
|
|
console.log(error); // for debug
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// response interceptor
|
|
service.interceptors.response.use(
|
|
(response) => {
|
|
const res = response.data;
|
|
|
|
if (res.status == 250) {
|
|
uni.showToast({
|
|
title: `提示${res.msg}`,
|
|
icon: "error",
|
|
duration: 1000,
|
|
});
|
|
}
|
|
|
|
if (res.code == 30) {
|
|
uni.showToast({
|
|
title: `token已经过期需要重新登录`,
|
|
icon: "error",
|
|
duration: 1000,
|
|
});
|
|
|
|
$store.dispatch("user/LoginOut", true);
|
|
|
|
return;
|
|
}
|
|
|
|
return res;
|
|
},
|
|
(error) => {
|
|
if (error.response && error.response.status === 503) {
|
|
// 统一处理所有 503 错误
|
|
console.log("服务器开小差了~");
|
|
uni.showToast({
|
|
title: `服务器开小差了~`,
|
|
icon: "error",
|
|
duration: 1000,
|
|
});
|
|
// 可以在这里显示全局通知或重试逻辑
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default service;
|