Back to Homepage
Thursday 22 August 2024
51

Axios: How to Send Form Data

Axios is a widely-used HTTP client for JavaScript, especially in front-end frameworks like React and Vue.js. It simplifies making HTTP requests to interact with APIs. One common use case is sending form data to a server. Whether you're dealing with simple text fields or complex multipart form data (such as file uploads), Axios provides an easy way to handle these requests.

Step-by-Step Guide to Sending Form Data

1. Install Axios:

  • First, install Axios in your project via npm or yarn:
npm install axios
  • Or using yarn:
yarn add axios

2. Prepare Your Form Data:

  • If you're sending form data from a web page, you'll typically gather the data from form inputs. Create an instance of FormData and append your fields:
const formData = new FormData();
     formData.append('username', 'exampleUser');
     formData.append('email', 'user@example.com');
  • If you're sending a file:
const fileInput = document.querySelector('input[type="file"]');
     formData.append('profileImage', fileInput.files[0]);

3. Send Form Data with Axios:

  • Use Axios to send a POST request with the form data. When sending FormData, Axios automatically sets the correct headers:
axios.post('https://example.com/submit', formData)
       .then(response => {
           console.log('Form submitted successfully:', response.data);
       })
       .catch(error => {
           console.error('Error submitting form:', error);
       });

4. Handle the Response:

  • After sending the form data, you can handle the server's response, which might include a success message, validation errors, or other feedback.

Examples of Sending Form Data with Axios

Example 1: Simple Text Form Submission

If you're working with a form that contains only text fields:

const formData = new FormData();
formData.append('name', 'John Doe');
formData.append('email', 'johndoe@example.com');

axios.post('https://example.com/api/submit', formData)
  .then(response => console.log('Form submitted:', response.data))
  .catch(error => console.error('Submission error:', error));

Example 2: Multipart Form Data (File Upload)

For forms that include file uploads:

const formData = new FormData();
formData.append('username', 'JaneDoe');
formData.append('profileImage', fileInput.files[0]);

axios.post('https://example.com/upload', formData)
  .then(response => console.log('File uploaded:', response.data))
  .catch(error => console.error('Upload error:', error));

Example 3: Custom Headers with Form Data

Sometimes, you may need to include custom headers in your request:

const formData = new FormData();
formData.append('token', 'your-auth-token');
formData.append('description', 'A brief description');

axios.post('https://example.com/upload', formData, {
    headers: {
        'Authorization': 'Bearer yourToken',
        'Content-Type': 'multipart/form-data'
    }
})
.then(response => console.log('Request succeeded:', response.data))
.catch(error => console.error('Request failed:', error));

References

By following this guide, you can efficiently send form data using Axios in your web applications, whether you're working with simple text fields or complex multipart forms.

Share:
Created by:
Author photo

Jorge García

Fullstack developer