In today’s article, I will show you how to send a POST request using URLSearchParams and the Axios library in React Native/Expo. In previous articles, I taught you how to make a GET request in React Native with Axios and how to perform a POST request with Axios in React Native.
To begin, you need to install the dependency:
expo install axios
Once installed, import the library in the component or screen where you want to use it:
import axios from "axios";
Now, let’s create the request:
// Headers of the request const config = { headers: { "Content-Type": "application/x-www-form-urlencoded" } }; // Parameters var urlencoded = new URLSearchParams(); urlencoded.append("parametro_1", "valor"); urlencoded.append("parametro_2", 2); // POST request axios.post("tu_url", urlencoded.toString(), config) .then(respuesta => { alert(JSON.stringify(respuesta.data)); }) .catch(error => { console.log('error', error); });
Let me explain the code:
First, we create the request headers, in this case, the “Content-Type”.
Then, we create the parameters using the “URLSearchParams()” object.
var urlencoded = new URLSearchParams(); urlencoded.append("parametro_1", "valor"); urlencoded.append("parametro_2", 2);
Next, we add the parameters to the request using “urlencoded.toString()”.
The response is received in the following line:
.then(respuesta => { alert(JSON.stringify(respuesta.data)); })
And if there is an error in the request, it is received in the line:
}).catch(error => { console.log('error', error); });
Please note that “tu_url” should be replaced with the actual URL where you want to send the POST request.