54 lines
1.2 KiB
JavaScript
54 lines
1.2 KiB
JavaScript
const Request = async (url, options = {}) => {
|
|
const {
|
|
method = "GET",
|
|
data = null,
|
|
headers = {},
|
|
...rest
|
|
} = options;
|
|
|
|
const defaultHeaders = {
|
|
"Content-Type": "application/json",
|
|
...headers
|
|
};
|
|
|
|
const config = {
|
|
method,
|
|
headers: defaultHeaders,
|
|
...rest
|
|
};
|
|
|
|
if (data && (method === "POST" || method === "PUT" || method === "PATCH")) {
|
|
config.body = JSON.stringify(data);
|
|
}
|
|
|
|
if (method === "GET" && data) {
|
|
const params = new URLSearchParams(data).toString();
|
|
url = url.includes("?") ? `${url}&${params}` : `${url}?${params}`;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(url, config);
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
const contentType = response.headers.get("content-type");
|
|
if (contentType && contentType.includes("application/json")) {
|
|
return await response.json();
|
|
}
|
|
|
|
return await response.text();
|
|
} catch (error) {
|
|
console.error("Request error:", error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
Request.get = (url, data, options = {}) =>
|
|
Request(url, { method: "GET", ...options });
|
|
|
|
Request.post = (url, data, options = {}) =>
|
|
Request(url, { method: "POST", data, ...options });
|
|
|
|
export { Request }; |