Onjsdev

Share


Axios Put Request


By onjsdev

Jul 20th, 2024

Axios is a popular javascript library for making HTTP requests both in web browsers and Nodejs environments. It provides a simpler approach compared to traditional fetch API.

On the other hand, a PUT request is a way to update or replace information in a server on the web. In Axios, you can easily send a PUT request using the axios.put method.

How To Install Axios

To make an PUT request with Axios, you will need to install Axios in your project. This can be done through various methods like CDN links or package managers such as npm or yarn.

npm install axios

How To Make An Axios PUT Request

Now, you can make a PUT request using the axios.put() method. In basic usage, this method takes two arguments: the URL you want to send the request to and the data to replace the existing data.

const url = 'https://example.com/api/resource'; // Replace with the actual URL
const data = {
  // Your data to update
  key1: 'value1',
  key2: 'value2'
};

axios.put(url, data)
  .then(response => {
    console.log('Response:', response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Here, the .then method is called if the request is successful, and if it exist, the response object contains response data in the response.data property, while the .catch method handles any errors that might occur during the request.

You can also use async/await for cleaner syntax and better readability.

const updateData = async () => {
  const url = 'https://example.com/api/resource'; // Replace with the actual URL
  const data = {
    key1: 'value1',
    key2: 'value2'
  };

  try {
    const response = await axios.put(url, data);
    console.log('Response:', response.data);
  } catch (error) {
    console.error('Error:', error);
  }
};

updateData();

How To Add Headers To Put Request

If you need to include headers (e.g., for authentication):

const url = 'https://example.com/api/resource'; // Replace with the actual URL
const data = {
  key1: 'value1',
  key2: 'value2'
};
const headers = {
  'Authorization': 'Bearer YOUR_ACCESS_TOKEN', // Replace with your token
  'Content-Type': 'application/json'
};

axios.put(url, data, { headers })
  .then(response => {
    console.log('Response:', response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Conclusion

That's it! You've successfully made a PUT request using Axios. You can adjust the code according to your specific API and data requirements.

Thank you for reading