Files
nl-base-app/src/utils/http.js

129 lines
3.1 KiB
JavaScript
Raw Normal View History

2026-01-14 12:57:30 +08:00
import axios from "axios";
// 获取存储的IP地址
const getBaseURL = () => {
const storedIP = uni.getStorageSync("apiBaseURL");
if (storedIP) {
// 如果存储的IP不包含协议自动添加http://
return storedIP.startsWith("http") ? storedIP : `http://${storedIP}`;
}
return import.meta.env.VITE_API_BASE_URL || "/api";
};
// 创建 axios 实例
const http = axios.create({
baseURL: getBaseURL(),
timeout: 10000,
headers: {
"Content-Type": "application/json",
},
});
// 设置IP地址的方法供外部调用
export const setBaseURL = (ip) => {
const baseURL = ip.startsWith("http") ? ip : `http://${ip}`;
http.defaults.baseURL = baseURL;
uni.setStorageSync("apiBaseURL", baseURL);
};
// 请求拦截器
http.interceptors.request.use(
(config) => {
// 每次请求前更新baseURL从存储中获取最新的IP
const storedIP = uni.getStorageSync("apiBaseURL");
if (storedIP) {
const baseURL = storedIP.startsWith("http") ? storedIP : `http://${storedIP}`;
config.baseURL = baseURL;
}
// 从本地存储获取 token
const token = uni.getStorageSync("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// 显示 loading
uni.showLoading({ title: "加载中..." });
return config;
},
(error) => {
uni.hideLoading();
return Promise.reject(error);
}
);
// 响应拦截器
http.interceptors.response.use(
(response) => {
uni.hideLoading();
const { data } = response;
// 根据业务状态码处理(可根据实际接口调整)
if (data.code === 200 || data.code === 0) {
return data;
}
// 业务错误提示
uni.showToast({
title: data.message || "请求失败",
icon: "none",
});
return Promise.reject(data);
},
(error) => {
uni.hideLoading();
// HTTP 错误处理
let message = "网络错误";
if (error.response) {
switch (error.response.status) {
case 401:
message = "登录已过期,请重新登录";
// 清除 token 并跳转登录页
uni.removeStorageSync("token");
uni.reLaunch({ url: "/pages/index/index" });
break;
case 403:
message = "没有权限访问";
break;
case 404:
message = "请求资源不存在";
break;
case 500:
message = "服务器错误";
break;
default:
message = error.response.data?.message || "请求失败";
}
} else if (error.code === "ECONNABORTED") {
message = "请求超时";
}
uni.showToast({ title: message, icon: "none" });
return Promise.reject(error);
}
);
// 封装请求方法
export const get = (url, params, config = {}) => {
return http.get(url, { params, ...config });
};
export const post = (url, data, config = {}) => {
return http.post(url, data, config);
};
export const put = (url, data, config = {}) => {
return http.put(url, data, config);
};
export const del = (url, params, config = {}) => {
return http.delete(url, { params, ...config });
};
export default http;