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

How to send form data with post request in axios?

7 个月前提问
3 个月前修改
浏览次数123

6个答案

1
2
3
4
5
6

当您使用 JavaScript 的 Axios 库来发送表单数据请求时,您需要使用 FormData API 来创建表单数据,并通过 Axios 发送 POST 请求。以下是如何使用 Axios 发送 FormData 的步骤:

  1. 创建一个 FormData 实例。
  2. 使用 append 方法添加键值对到表单数据中。
  3. 配置 Axios 请求,将 FormData 实例设置为请求体。
  4. 发送请求,并处理响应或者捕获错误。

下面是一个使用 Axios 发送表单数据的示例代码:

javascript
// 引入 axios import axios from 'axios'; // 创建 FormData 实例 const formData = new FormData(); // 添加一些键值对数据 formData.append('username', 'johndoe'); formData.append('avatar', fileInput.files[0]); // 假设有一个文件输入 // 配置 Axios 请求 const config = { headers: { // 必须包含此头部来表明发送的是 multipart/form-data 'Content-Type': 'multipart/form-data' } }; // 发送 POST 请求 axios.post('https://yourapi.com/upload', formData, config) .then((response) => { // 请求成功,处理响应 console.log('Upload successful', response); }) .catch((error) => { // 请求失败,处理错误 console.error('Upload failed', error); });

在这个例子中,我们首先导入了 Axios 库。创建了一个 FormData 对象,并使用 append 方法添加了一些键值对数据,其中包括一个用户名和一个文件对象。然后我们配置了 Axios 请求,特别是设置了 Content-Typemultipart/form-data,这是发送包含文件的表单数据时的必要步骤。最后,我们通过 axios.post 方法发送请求,并提供了 URL、formData 对象和配置对象。请求成功或失败时,我们使用 .then() 方法和 .catch() 方法来处理响应或错误。

2024年6月29日 12:07 回复

您可以使用FormData()发布 axios 数据,例如:

shell
var bodyFormData = new FormData();

然后将字段添加到要发送的表单中:

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

如果您要上传图像,您可能需要使用.append

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

然后就可以使用axios post方法了(可以相应修改)

shell
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); });

相关 GitHub 问题:

无法获得带有 'Content-Type': 'multipart/form-data' 的 .post 来工作 @ axios/axios

2024年6月29日 12:07 回复

就我而言,我必须将边界添加到标题中,如下所示:

shell
const form = new FormData(); form.append(item.name, fs.createReadStream(pathToFile)); const response = await axios({ method: 'post', url: 'http://www.yourserver.com/upload', data: form, headers: { 'Content-Type': `multipart/form-data; boundary=${form._boundary}`, }, });

如果您使用 React Native,此解决方案也很有用。

2024年6月29日 12:07 回复

查看查询字符串

您可以按如下方式使用它:

shell
var querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
2024年6月29日 12:07 回复

上传(多个)二进制文件

Node.js

当您想通过 发布文件multipart/form-data(尤其是多个二进制文件)时,事情会变得复杂。下面是一个工作示例:

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() })
  • 而不是headers: {'Content-Type': 'multipart/form-data' }我更喜欢headers: formData.getHeaders()
  • 我使用asyncawait上面,如果你不喜欢它们,你可以将它们更改为普通的 Promise 语句
  • 为了添加您自己的标题,您只需headers: { ...yourHeaders, ...formData.getHeaders() }

新增内容如下:

浏览器

浏览器的FormData与 NPM 包“form-data”不同。以下代码在浏览器中适用于我:

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 回复

2020 ES6 的做法

将 html 中的表单绑定到数据中,如下所示:

数据:

shell
form: { name: 'Joan Cap de porc', email: 'fake@email.com', phone: 2323, query: 'cap d\ou' file: null, legal: false },

提交时:

shell
async submitForm() { const formData = new FormData() Object.keys(this.form).forEach((key) => { formData.append(key, this.form[key]) }) try { await this.$axios.post('/ajax/contact/contact-us', formData) this.$emit('formSent') } catch (err) { this.errors.push('form_error') } }
2024年6月29日 12:07 回复

你的答案