When using the Axios library in JavaScript to send form data requests, you should utilize the FormData API to construct the form data and send a POST request through Axios. Below are the steps to send FormData using Axios:
- Create a
FormDatainstance. - Use the
appendmethod to add key-value pairs to the form data. - Configure the Axios request to set the
FormDatainstance as the request body. - Send the request and handle the response or catch errors.
Here is an example of sending form data using Axios:
javascript// Import Axios library import axios from 'axios'; // Create FormData instance const formData = new FormData(); // Add some key-value pairs formData.append('username', 'johndoe'); formData.append('avatar', fileInput.files[0]); // Assuming a file input is present // Configure Axios request const config = { headers: { // Required to specify that multipart/form-data is being sent 'Content-Type': 'multipart/form-data' } }; // Send POST request axios.post('https://yourapi.com/upload', formData, config) .then((response) => { // Request successful, handle response console.log('Upload successful', response); }) .catch((error) => { // Request failed, handle error console.error('Upload failed', error); });
In this example, we first import the Axios library. We create a FormData object and use the append method to add key-value pairs, including a username and a file object. Then, we configure the Axios request, specifically setting Content-Type to multipart/form-data, which is required for sending form data that includes files. Finally, we send the request using the axios.post method, providing the URL, the formData object, and the configuration object. When the request is successful or fails, we handle the response or error using the .then() and .catch() methods respectively.