我在React中使用axios尝试将文件发送到服务器。有人可以告诉我我在做什么错。没有错form
变量返回一个空对象。我完全迷住了。
路径:React submit call
handleSubmit(event) {
event.preventDefault();
this.props.uploadProducts(supplier_id, this.fileInput.current.files[0]);
}
路径:uploadProducts
export const uploadProducts = (supplier_id, file) => (dispatch, getState) => {
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_file', file);
console.log(form);
axios
.post('http://localhost:3000/products', form, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
};
路径:Server
router.post('/products', async function (req, res, next) {
console.log('res', req.body);
});
答案 0 :(得分:0)
FormData API不会通过控制台直接记录它来返回您的值。它具有一些辅助函数,然后是一些迭代器,以提取其值。检查更多:formData MDN
您的axios帖子似乎与您的路由器端点不匹配。 axios还是一个Promise库,因此您使用then
和catch
来处理解决和拒绝操作。
axios
.post('http://localhost:3000/upload/supplier/products', form, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => console.log(res))
.catch(err => console.log(err))
如果将函数定义为async
,则可以使用await
并包装在try catch块中:
try {
const response = await axios
.post('http://localhost:3000/upload/supplier/products', form, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
console.log(response)
} catch (e) {
console.log(e)
}