skip to Main Content

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


  1. 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:

    async function fetchData(url = "", method = "GET", data = null) {
       
        const options = {
            method: method,
            mode: "cors",
            credentials: "include",
            headers: {
                "Content-Type": "application/json",
            }
        };
    
      
        if (method === "POST" && data !== null) {
            options.body = JSON.stringify(data);
        }
    
        const response = await fetch(url, options);
    
        return response.json();
    }
    

    Example for a GET request:

    fetchData("https://example.com/data")
        .then(data => console.log(data))
        .catch(error => console.error('Error:', error));
    

    Example for a POST request:

    fetchData("https://api.example.com/submit", "POST", {name: "John", age: 30})
        .then(data => console.log(data))
        .catch(error => console.error('Error:', error));
    
    Login or Signup to reply.
  2. I guess you could simply write a third function that does a send

    like:

    function send(url, options) {
      if (!url) {
        throw 'url not specified';
      }
      return fetch( url, {
        mode: 'cors',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json'
        },
        ...options });
    }
    
    function getData(url) {
      return send( url, { method: 'GET' });
    }
    
    function postData(url, body) {
      return post( url, { method: 'POST', body: body ? JSON.stringify( body ) : null });
    }

    this would allow you to add more methods afterwards and keeps the headers logic in one place

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search