Reading time: 2 minutes
In order to communicate with our remote server (backend) using React Native, we need to make an asynchronous call.
//Headers, if we want to add a token, we have to include it in these headers. var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); javascript Copy code //Parameters to send var urlencoded = new URLSearchParams(); urlencoded.append("nombre", nombre); urlencoded.append("email", email); //Request object var requestOptions = { method: 'POST', headers: myHeaders, body: urlencoded }; //URL and request object for fetch fetch("https://www.urlmiweb.com/post_con_form", requestOptions) .then(response => response.text()) .then(result => console.log(result) ) .catch(error => console.log('error', error));
In this example, I’m sending data in a FORM object using the fetch method in JavaScript.
First, we create the headers:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
In this case, we indicate that we are sending a FORM (like web forms).
Then, we add the parameters to our FORM:
var urlencoded = new URLSearchParams();
urlencoded.append("nombre", nombre);
urlencoded.append("email", email);
Now, we create an object with all the attributes of the call, including the POST method, the headers we created before, and the body with the filled FORM object:
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
We make the call using the fetch method in JavaScript, providing the URL and the options:
fetch("https://www.urlmiweb.com/post_con_form", requestOptions)
Inside the fetch call, we have different parts. If the call is successful, we invoke this method:
.then(result =>
console.log(result)
)
Asynchronously, we can execute what we add inside result => (for example, another function), and the server response is stored in the result variable.
If the call fails, the error method is invoked:
.catch(error => console.log('error', error));