UNPKG

fetchbee

Version:

A lightweight JS library to simplify all kinds of API calls.

36 lines (28 loc) 867 B
async function postFetchWithMethod(method, url, body = {}, options = {}) { if (!url || typeof url !== "string") { console.warn(`${method} request: Invalid or missing URL.`); return null; } const { query = {}, headers = {}, ...rest } = options; // Build query string const queryString = new URLSearchParams(query).toString(); const fullUrl = queryString ? `${url}?${queryString}` : url; try { const response = await fetch(fullUrl, { method, headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body), ...rest }); if (!response.ok) { throw new Error(`${method} failed with status ${response.status}`); } return await response.json(); } catch (error) { console.error(`${method} request error:`, error.message); return null; } }