Make a GET Request from React Native

Tiempo de lectura: < 1 minuto

Reading time: < 1 minute

If we want to retrieve data from a remote server, we can use the following code:

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

var requestOptions = {
    method: 'GET',
    headers: myHeaders
};

fetch("https://www.miweb.com/getPerson", requestOptions)
    .then(response => response.json())
    .then((responseJson) => {
        alert(responseJson);
    })
    .catch(error => console.log(error));

First, we create the headers that we can use:

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

Then, we set the request options:

var requestOptions = {
    method: 'GET',
    headers: myHeaders
};

In this case, we specify that it is a GET request and it has the headers created before.

And now we send the request:

fetch("https://www.miweb.com/getPerson", requestOptions)
    .then(response => response.json())
    .then((responseJson) => {
        alert(responseJson);
    })
    .catch(error => console.log(error));

We specify the URL where the resource we want to retrieve from our server is located and attach the request options.

Inside:

.then((responseJson) => {
alert(responseJson);
})

We receive the response, in this case, we display an alert with the response.

If there’s an error, it would be caught by:

catch(error => console.log(error));

Leave a Comment