CÓMO ENVIAR DATOS EN SOLICITUDES GET Y POST CON JAVASCRIPT FETCH API JSON
Sending Requests with Fetch API
To send a GET request with Fetch API, use the following code:
fetch( 'https://domain.com/path/?param1=value1¶m2=value2' )
.then( response => response.json() )
.then( response => {
// Do something with response.
} );
To send a POST request, use the following code:
const params = {
param1: value1,
param2: value2;
};
const options = {
method: 'POST',
body: JSON.stringify( params )
};
fetch( 'https://domain.com/path/', options )
.then( response => response.json() )
.then( response => {
// Do something with response.
} );
You can see the main difference between GET and POST requests is how the parameters are passed to the fetch call. In most cases, developers expect to pass an object of parameters and send requests in a beautiful syntax like this:
const params = {
param1: value1,
param2: value2;
};
const response = get( url, params );
// or
const response = post( url, params );
To do that, we need some code to transform the original code with fetch to the new syntax.
Creating get and post Functions
Because the codes that send requests are similar between GET and POST, we’ll create a common function request to make a request first. And then use it to create get and post functions like this:
const request = ( url, params, method ) => {
// All logic is here.
};
const get = ( url, params ) => request( url, params, 'GET' );
const post = ( url, params ) => request( url, params, 'POST' );
Now it’s time to build the request function.
Note that for each function, we have a different way to construct parameters: they’re in the URL for GET, and in the body for POST. Thanks to URLSearchParams we can transform an object to a query string for the GET request.
Here is the first version:
const request = ( url, params = {}, method = 'GET' ) => {
let options = {
method
};
if ( 'GET' === method ) {
url += '?' + ( new URLSearchParams( params ) ).toString();
} else {
options.body = JSON.stringify( params );
}
return fetch( url, options ).then( response => response.json() );
};
const get = ( url, params ) => request( url, params, 'GET' );
const post = ( url, params ) => request( url, params, 'POST' );
The above code returns a promise, and you can use it in your app like this:
get( 'https://domain.com/path', { param1: value1, param2: value2 } )
.then( response => {
// Do something with response.
} );
///////////////////////
Comentarios
Publicar un comentario