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.
1. Install Axios:
npm install axios
yarn add axios
2. Prepare Your Form Data:
FormData and append your fields:
const formData = new FormData();
formData.append('username', 'exampleUser');
formData.append('email', 'user@example.com');
const fileInput = document.querySelector('input[type="file"]');
formData.append('profileImage', fileInput.files[0]);
3. Send Form Data with Axios:
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:
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));
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));
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));
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.
Jorge García
Fullstack developer