87 lines
2.0 KiB
JavaScript
87 lines
2.0 KiB
JavaScript
import axios from "axios";
|
|
import config from "../config/config";
|
|
import axiosAdapterUniapp from "axios-adapter-uniapp";
|
|
import $store from "../store/index";
|
|
import qs from "qs";
|
|
|
|
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");
|
|
}
|
|
if (
|
|
config.data &&
|
|
config.headers["Content-Type"] ===
|
|
"application/x-www-form-urlencoded;charset=UTF-8"
|
|
) {
|
|
config.data = qs.stringify(config.data);
|
|
}
|
|
|
|
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 && res.status == 250) {
|
|
uni.$u.toast(`提示:${res.msg}`);
|
|
|
|
// uni.showToast({
|
|
// title: `提示${res.msg}`,
|
|
// icon: "error",
|
|
// duration: 2000,
|
|
// });
|
|
}
|
|
|
|
if (res && res.code == 30) {
|
|
uni.$u.toast(`token已经过期需要重新登录`);
|
|
|
|
// 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;
|