Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use fetch to send get request with data object

I'm using Fetch (Fetch API) in a project and I would like to, for consistence purposes, create a function that receives all the parameters such as method, url and data and creates the correct request, depending if it's a GET or a POST request.

Is it possible, using Fetch, to send a data object that for the GET request, converts data into and string with the parameters and if it is a POST request, it just sends the data object in the body?

It would look like this:

fetch ('/test', {
        method: 'GET',
        data: {
           test: 'test'
        }
});

This doubt was inspired by this jQuery ajax behaviour:

$.ajax({
   url: '/test',
   method: 'GET',
   data: {
      test: 'test'
   }
});

This would produce this request:

'/test/?test=test'
like image 480
Defesa Esquerdo Avatar asked Dec 14 '22 04:12

Defesa Esquerdo


1 Answers

If I pass the data object as normal in the fetch constructor for a GET request, would it send the request like the example I gave '/test/?test=test'

If you want to add query string to a fetch request :

From the SPEC

var url = new URL("https://a.com/method"),
params = {a:1, b:2}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url)

this will produce a request :

enter image description here

like image 162
Royi Namir Avatar answered Jan 07 '23 02:01

Royi Namir