Cómo hacer un POST con Axios en React Native

Tiempo de lectura: 2 minutos

Reading time: < 1 minute

In the previous tutorial, I showed you how to make a GET request using the Axios library in React Native: Making a GET Request in React Native with Axios

Now let’s see how to make a POST request.

First, we need to install Axios:

expo install axios

Once installed, import it into the screen or component where you want to use it:

import axios from "axios";

Now let’s create the POST request:

// Object to be sent
const data = {
  id: 1
};

// POST request
axios.post("your_url", { data })
  .then(response => {
    console.log(response);
  });

Replace “your_url” with the URL where you want to send the POST request. The asynchronous response will be received in the .then(response => part.

If you want to add headers, you can do the following:

// Create headers
const config = {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "TOKEN": "123456789"
  }
};

// Object to be sent
const data = {
  id: 1
};

axios.post("your_url", { data }, config)
  .then(response => {
    console.log(response);
  });

It would look like this:

import axios from "axios";

// Create headers
const config = {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "TOKEN": "123456789"
  }
};

// Object to be sent
const data = {
  id: 1
};

axios.post("your_url", { data }, config)
  .then(response => {
    console.log(response);
  });

In the previous tutorial, I showed you how to make a GET request using the Axios library in React Native. Now let’s learn how to make a POST request.

First, we need to install Axios by running the following command:

expo install axios

Once Axios is installed, import it into your screen or component:

import axios from "axios";

Now, let’s create the POST request:

// Object to be sent
const data = {
  id: 1
};

// POST request
axios.post("your_url", { data })
  .then(response => {
    console.log(response);
  });

Replace "your_url" with the URL where you want to send the POST request. The response will be received asynchronously in the .then block.

If you want to include headers in the request, you can do so by creating a configuration object:

// Create headers
const config = {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "TOKEN": "123456789"
  }
};

// Object to be sent
const data = {
  id: 1
};

// POST request with headers
axios.post("your_url", { data }, config)
  .then(response => {
    console.log(response);
  });

That’s it! You have learned how to make a POST request using Axios in React Native.

Leave a Comment