plc_control/web/js/api.js

34 lines
726 B
JavaScript

import { dom } from "./dom.js";
export function setStatus(text) {
dom.statusText.textContent = text;
}
export async function apiFetch(url, options = {}) {
const response = await fetch(url, {
headers: { "Content-Type": "application/json" },
...options,
});
if (!response.ok) {
throw new Error((await response.text()) || response.statusText);
}
if (response.status === 204) {
return null;
}
const contentType = response.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return response.json();
}
return response.text();
}
export function withStatus(task) {
return task.catch((error) => {
setStatus(error.message || "请求失败");
});
}