Search code examples
javascriptfetch

Using Fetch but have a key param at the end of the URL to GET and POST


I am using fetch but my company now has a keyAccess key param that I have to put at the end of the url to POST and GET. I am not sure how to do this in either.

In my POST, I am sending data in the body already:

let myUrl = "http://www.example.com";
    fetch(myUrl, {
       method: "POST",
       headers: {
          "Content-Type": "application/json"
       }, 
       body: JSON.stringify(data);
    }

and in my GET, would I just append it to the url like? :

fetch(myUrl + 'keyAccess=938741')

Solution

  • You could use the URL interface to create your url and with the searchParams method you could append the key value pairs that you need. This way you don't have to check if the URL already has GET parameters.

    const url = new URL("http://www.example.com");
    url.searchParams.append("keyAccess", 938741);
    
    console.log(url);