Send FormData request using Axios in Vue
In this, using Axios to send FormData requests can implement functions such as file upload and form submission. Axios is a widely used HTTP client library that provides a simple and powerful way to communicate with backend APIs. This article will explain how to use Axios to send FormData requests in Vue.
Install Axios
First, we need to install Axios. Run the following command in the root directory of the Vue project:
plaintextCopy code npm install axios
or
plaintextCopy code yarn add axios
After the installation is complete, we can import and use it in the Vue component.
Create a FormData object
When sending a request containing file or form data, we need to create a FormData object. FormData is an API for building form data when sending a request. It can interact with form elements through JavaScript, thus wrapping the form data into key-value pairs and being correctly encoded for transmission in HTTP requests. Here is a sample code for creating a FormData object in a Vue component:
javascriptCopy code // Import axiosimport axios from 'axios'; // Create FormData object in Vue componentconst formData = new FormData(); ('name', ); ('avatar', );
In the above example code, we first import axios and then create aformDataObject. useappend()Method, we added key-value pairs to the FormData object. in,nameis the name of the form field.is the value of the form field.avataris the name of the file upload field.is a file object.
Send a FormData request
Once we have the FormData object, we can use Axios to send the request. Here is a sample code that demonstrates how to use Axios to send a FormData request:
// Import axiosimport axios from 'axios'; // Send FormData request in Vue component('/api/submit', formData) .then(response => { (); }) .catch(error => { (error); });
In the above example code, we use()Method sends a POST request. The first parameter is the URL of the API, and the second parameter is the FormData object. Then, we use.then()and.catch()Methods handle request responses and errors.
Pass the request header information
When sending a FormData request, you may need to set the request header information, such as settingContent-Typeformultipart/form-data. It can be set by setting the default request header of Axios or separately when requesting. Here is a sample code for setting the request header:
javascriptCopy code // Import axiosimport axios from 'axios'; // Set request header['Content-Type'] = 'multipart/form-data'; // Send FormData request in Vue component('/api/submit', formData) .then(response => { (); }) .catch(error => { (error); });
In the above example code, we useSet the default request header. When we send a FormData request, Axios will automatically add the specified request header information.
User uploads avatar. We can achieve this function by sending FormData requests in conjunction with Axios. The following is a sample code that demonstrates how to implement the function of uploading user avatars in Vue components:
<template> <div> <input type="file" @change="handleFileChange"> <button @click="uploadAvatar">Upload avatar</button> </div> </template> <script> import axios from 'axios'; export default { data() { return { avatarFile: null }; }, methods: { handleFileChange(e) { = [0]; }, uploadAvatar() { const formData = new FormData(); ('avatar', ); ('/api/uploadAvatar', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { ('The avatar upload was successful', ); }) .catch(error => { ('Avatar upload failed', error); }); } } }; </script>
In the above example code, we first add a file upload input tag and a button to the template, and the user can select the local file to upload the avatar. Then, a Vue component is definedavatarFileData attributes to store the file selected by the user. When the user selects the file, we passhandleFileChangeMethods to store file objects inavatarFilemiddle. Then, when the user clicks the button "Upload avatar", it triggersuploadAvatarmethod. existuploadAvatarIn the method, we create a FormData object to add the file object selected by the user to FormData. Then use Axios to send a POST request to/api/uploadAvatarinterface and set the request headerContent-Typeformultipart/form-data. Finally, we pass.then()and.catch()Methods handle upload success and failure. In this way, users can upload avatar by selecting local files, thus realizing the function of uploading user avatars. Hopefully this example can help you better understand the practical application scenarios of sending FormData requests in Vue in combination with Axios.
Axios is a Promise-based HTTP client that sends HTTP requests. It can be used in both the browser and the environment and provides some powerful functions such as intercepting requests and responses, converting requests and response data, etc. Here are some of the main features and usages of Axios:
- Easy to use: Axios provides a clean and simple API that is easy to learn and use.
- Supports browser and: Axios can be used in both the browser and environment. It is implemented based on the browser's built-in XMLHttpRequest object. In the environment, it uses a module called http to send HTTP requests.
- Promise API: Axios uses Promise to handle asynchronous operations, and can use the then and catch methods to handle callbacks that successfully and fail.
- Interceptor: Axios provides a powerful interceptor mechanism that allows requests or responses to be intercepted and modified before they are sent or processed. With the interceptor, we can add a common request header before the request is sent, or preprocess the returned data before the response is returned.
- Convert request and response data: Axios can convert request and response data before sending a request and returning a response. By default, it converts request and response data into JSON format.
- Error handling: Axios provides a unified error handling mechanism that can uniformly handle requests or response errors.
- Cancel Request: Axios allows us to cancel an ongoing request. It can be called by creating a token that cancels the request and passing it to Axios when the request is sent, and then calling the cancel method when the request needs to be cancelled.
- Configuration request: Axios allows us to provide some configuration options when making a request, such as request timeout time, request header, URL parameters, etc. Here is a simple example of sending GET requests using Axios in your browser:
('/api/data') .then(response => { (); }) .catch(error => { (error); });
In the example above, we useThe method sent a GET request to/api/datainterface. pass.thenThe method handles the callback that requests successfully, and the response data can be accessed in the callback function. and.catchThe method is used to handle the callback that fails the request and can obtain error information.
Conclusion
By using Axios and FormData combinations, we can easily send requests containing file or form data in a Vue project. Axios provides a simple and powerful API to handle HTTP requests, while FormData provides an API for building form data. This makes it very easy to implement features such as file upload and form submission in Vue.
This is the article about how to use Axios to send FormData requests in Vue. For more related contents for sending FormData requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!