Use Fetch to Send a Receive Request Using a Data Object

I use Fetch ( Fetch API ) in the project, and I would like, for sequence purposes, to create a function that receives all parameters such as method, url and data, and creates the correct request, depending on the GET or POST request.

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

It will look like this:

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

This doubt was inspired by this jQuery ajax behavior:

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

This will call this request:

'/test/?test=test'
+4
source share
2 answers

GET, , , '//? =

:

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)

:

enter image description here

+5

Url:

var url = new URL("/test/")
Object.keys({test: 'test', a: 1}).forEach(key => url.searchParams.append(key, params[key]))
fetch(url);

, :

var params = {test: 'test', a: 1},
    qs = Object.keys(params).reduce(function(_qs, k, i){ return _qs + '&' + k + '=' + params[k]; }, '').substring(1);

console.log(qs)
+1

Source: https://habr.com/ru/post/1653115/


All Articles