2026-04-23 16:23:40 +08:00
|
|
|
// api.js - 跨端统一 API 调用层
|
|
|
|
|
|
|
|
|
|
const isWebView2 = () => {
|
|
|
|
|
return window.isWebView2 === true;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const getBaseUrl = () => {
|
|
|
|
|
if (isWebView2()) {
|
|
|
|
|
return "app://api/";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return "https://your-production-api.com/api/";
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
async function callApi(endpoint, options = {}) {
|
|
|
|
|
const url = getBaseUrl() + endpoint;
|
|
|
|
|
const fetchOptions = {
|
|
|
|
|
method: options.method || "GET",
|
|
|
|
|
headers: {
|
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
|
...(options.headers || {})
|
|
|
|
|
},
|
|
|
|
|
...(options.body && { body: JSON.stringify(options.body) })
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const token = localStorage.getItem("authToken");
|
|
|
|
|
if (token) {
|
|
|
|
|
fetchOptions.headers.Authorization = `Bearer ${token}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const response = await fetch(url, fetchOptions);
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
console.log(data)
|
|
|
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new Error(data.error || `HTTP ${response.status}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return data;
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error(`API call failed: ${endpoint}`, err);
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
window.api = {
|
2026-04-23 17:25:31 +08:00
|
|
|
getUser: () => callApi("getUser?t=1"),
|
2026-04-24 11:56:02 +08:00
|
|
|
processData: (input) => callApi("processData", { method: "POST", body: { input } }),
|
|
|
|
|
wData: (input) => callApi("wData", { method: "POST", body: { input } }),
|
2026-04-23 16:23:40 +08:00
|
|
|
};
|