Skip to content

Instantly share code, notes, and snippets.

@kawsaramin101
Last active May 12, 2024 06:24
Show Gist options
  • Save kawsaramin101/7861d36380e360872798f0b5e7227ed6 to your computer and use it in GitHub Desktop.
Save kawsaramin101/7861d36380e360872798f0b5e7227ed6 to your computer and use it in GitHub Desktop.
json Fetch.js
async function jsonFetch(url, options) {
if (options.json) {
options.body = JSON.stringify(options.body);
options.headers = {
...options.headers,
"Content-Type": "application/json",
};
delete options.json;
}
return await fetch(url, options);
}
// Example usage
async function fetchData() {
try {
const response = await jsonFetch("https://example.com/api", {
json: true,
body: { key: "value" },
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment