You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* https://www.uviewui.com/js/http.html
*/
import store from "@/store";
module.exports = (vm) => {
// 初始化请求配置
uni.$u.http.setConfig((config) => {
/* config 为默认全局配置*/
config.baseURL = "http://py12306.learnerhub.net"; // api 根域名,本地开发大概就是 localhost(看你怎么启动的后端服务器)
return config;
});
// 请求拦截
uni.$u.http.interceptors.request.use(
(config) => {
const authToken = uni.getStorageSync("auth-token");
if (authToken) {
config.header.Authorization = `Bearer ${authToken}`;
}
return config;
},
(config) => {
return Promise.reject(config);
}
);
// 响应拦截,对响应成功做点什么 可使用 async await 做异步操作
uni.$u.http.interceptors.response.use(
(response) => {
const data = response.data || {};
if (data.code === 0) {
return Promise.resolve(data);
} else {
if ([110001, 110003, 110005].includes(data.code)) {
// 以上 code 都是用户 auth 有问题,清空一下 store 数据
store.dispatch("revertAuth");
}
uni.hideLoading();
uni.showToast({
icon: "error",
duration: 2000,
title: data.msg || response.msg,
});
return Promise.reject(response);
}
},
(response) => {
uni.hideLoading();
// 对响应错误做点什么 statusCode !== 200
const data = response.data || {};
uni.showToast({
icon: "error",
duration: 2000,
title: data.msg || response.msg,
});
return Promise.reject(response);
}
);
};