Last active
May 12, 2024 06:24
-
-
Save kawsaramin101/7861d36380e360872798f0b5e7227ed6 to your computer and use it in GitHub Desktop.
json Fetch.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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