javascript - 如何为 Object 中的数组数据实现 New FormData() 以使用 Axios、ReactJs 执行 POST 方法?
问题描述
在后端,我使用 multer 上传多个文件/图像,我尝试使用 Postman 并且它可以工作。但是当我使用reactjs在前端应用它时,我很困惑
示例案例:
state = {
name: 'product1',
price: '200',
images: [{name: "1.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
{name: "2.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
files: [{name: "1.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
{name: "2.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
}
handleSubmit = () => {
const { name, price, images, files} = this.state
const body = new FormData()
body.append('name', name)
body.append('price', price)
images.map((file, i) => body.append('images[i]', file[i])) // not work
files.map((file, i) => body.append('files[i]', file[i])) // not work
axios.post(`http://localhost:3000/api/v1/add`, body)
.then((res) => res.data.data)
// result {"name":"roduct1","price":"200","images":[{},{}],"files":[{},{}]}
}
解决方案
可以这样通过 axios 发出 POST 请求:
var bodyFormData = new FormData();
bodyFormData.set('userName', 'Fred');
bodyFormData.append('image', imageFile);
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);
});
它还多次观察到 localhost 不能与 axios 一起使用。相反,您需要使用 IP 地址。如果假设您的 IP 地址192.23.43.45
比 URL 变为http://192.23.43.45:3000/api/v1/add
. 所以,你可以试试这个方法
推荐阅读
- java - 尝试在 Chrome 选项上设置功能时,它没有列出 .setCapability 方法
- python-3.x - 在 eval() 中未定义名称“self”
- c++ - boost::icl::interval 和 boost::numeric::interval 是否有可用的适配层?
- php - “在将此参数添加到参数时,无法猜测如何从参数“person_id”的请求信息中获取 Doctrine 实例
- java - 是否有一种流行的技术可以对具有泛型类型但仅限于数字的数组的元素求和?
- javascript - 构建捆绑包时如何删除未使用的代码?
- pycharm - PyCharm:解析 docker-compose.yml 时出错 docker-compose 配置失败
- python - 为什么 Online Python Tutor 将这个不可变整数以图形方式呈现为两个不同的整数?
- c++ - 在 C++ 中声明函数指针的 typedef
- node.js - 如何避免多个 Mongoose 操作的嵌套承诺?