I have built a function to call fetch with all the parameters I require set up. It works flawlessly but I want to improve it a bit. Currently I have two versions of it, one for GET and another for POST method. This is because for POST I need to pass a body while for GET no. I’d like to make it so that the body parameter in the function becomes optional and included in fetch only if set if it is a GET request.
This is the relevant part in case of GET
async function getData(url = "") {
const response = await fetch(url, {
method: "GET",
mode: "cors",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
});
this is the relevant part in case of POST
async function postData(url = "", data = {}) {
const response = await fetch(url, {
method: "POST",
mode: "cors",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
2
Answers
Here’s how you can create a unified function called fetchData that handles both GET and POST requests, as well as potentially other HTTP methods:
Example for a GET request:
Example for a POST request:
I guess you could simply write a third function that does a
send
like:
this would allow you to add more methods afterwards and keeps the headers logic in one place