乐闻世界logo
搜索文章和话题

How to send form data with post request in axios?

3个答案

1
2
3

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:

  1. Create a FormData instance.
  2. Use the append method to add key-value pairs to the form data.
  3. Configure the Axios request to set the FormData instance as the request body.
  4. 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.

2024年6月29日 12:07 回复

Node.js

When you want to submit files using multipart/form-data (especially multiple binary files), it becomes more complex. Here is a working example:

shell
const FormData = require('form-data') const fs = require('fs') const path = require('path') const formData = new FormData() formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json') formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png') await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData, { headers: formData.getHeaders() })
  • Instead of headers: {'Content-Type': 'multipart/form-data' }, I prefer headers: formData.getHeaders()
  • I use async and await as shown above, but if you prefer, you can replace them with regular Promise-based code.
  • To add your own headers, you can simply use headers: { ...yourHeaders, ...formData.getHeaders() }

The following is new content:

Browser

The browser's FormData is different from the NPM package 'form-data'. The following code works for me in the browser:

HTML:

shell
<input type="file" id="image" accept="image/png"/>

JavaScript:

shell
const formData = new FormData() // add a non-binary file formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json') // add a binary file const element = document.getElementById('image') const file = element.files[0] formData.append('files[]', file, file.name) await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)

2024年6月29日 12:07 回复

You can use FormData() to send form data with axios, for example:

javascript
var bodyFormData = new FormData();

Then add fields to the FormData object:

javascript
bodyFormData.append('userName', 'Fred');

If you want to upload an image, you may need to use .append:

javascript
bodyFormData.append('image', imageFile);

Then you can use the axios post method (which can be modified accordingly):

javascript
axios({ method: "post", url: "myurl", data: bodyFormData, headers: { "Content-Type": "multipart/form-data" }, }) .then(function (response) { //handle success console.log(response); }) .catch(function (response) { //handle error console.log(response); });

Related GitHub issue:

Unable to get the .post to work with 'Content-Type': 'multipart/form-data' @ axios/axios

2024年6月29日 12:07 回复

你的答案