Axios is a popular JavaScript library used for making HTTP requests. It provides an easy-to-use API for sending data to servers, including form data. In this tutorial, we will explore how to send form data using Axios.
Introduction to Form Data
Form data is used to send data from a client (usually a web browser) to a server. This data can include text input fields, checkbox values, file uploads, and more. When sending form data, the Content-Type
header of the request must be set to multipart/form-data
, which allows the server to parse the data correctly.
Using FormData with Axios
To send form data using Axios, you can use the FormData
API. The FormData
API provides a way to create and manage form data, including adding fields and files.
Here is an example of how to use FormData
with Axios:
const formData = new FormData();
formData.append('userName', 'Fred');
formData.append('userEmail', '[email protected]');
axios({
method: 'post',
url: '/addUser',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
In this example, we create a new FormData
object and append two fields to it: userName
and userEmail
. We then pass the formData
object as the data
property of the Axios request.
Adding Files to FormData
To add files to FormData
, you can use the append
method with the file object. Here is an example:
const formData = new FormData();
const fileInput = document.getElementById('file');
const file = fileInput.files[0];
formData.append('file', file);
axios({
method: 'post',
url: '/uploadFile',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
In this example, we get a reference to the input
element with the id file
, and then get the first file from the files
property. We then append the file to the FormData
object using the append
method.
Using application/x-www-form-urlencoded Format
If you need to send data in the application/x-www-form-urlencoded
format, you can use the URLSearchParams
API or a library like qs
.
Here is an example of how to use URLSearchParams
with Axios:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
Alternatively, you can use the qs
library:
const qs = require('qs');
const data = { 'bar': 123 };
axios.post('/foo', qs.stringify(data));
Conclusion
In this tutorial, we learned how to send form data using Axios. We covered the basics of form data, including how to use FormData
and add files to it. We also explored how to use the application/x-www-form-urlencoded
format with Axios.
By following the examples in this tutorial, you should be able to send form data using Axios in your own applications.