Javascript 如何使用Axios、ReactJs为Object中的数组数据实现New FormData(),以执行POST方法?
在后端,我使用multer上传多个文件/图像,我尝试过使用Postman,效果很好。但当我使用reactjs在前端应用它时,我感到困惑 示例案例:Javascript 如何使用Axios、ReactJs为Object中的数组数据实现New FormData(),以执行POST方法?,javascript,reactjs,express,axios,multer,Javascript,Reactjs,Express,Axios,Multer,在后端,我使用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 Indoc
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
。因此,您可以尝试这种方法您可以通过以下方式通过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
。那么,你可以试试这种方法@Najih解决方案对你有帮助吗?@Najih解决方案对你有帮助吗?