reactjs - 在 react app 中使用 axios 向服务器发送文件
问题描述
我在 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);
});
解决方案
FormData API 不会通过控制台直接记录它来返回您的值。它有一些辅助函数,其中一些是迭代器,以提取其值。查看更多:formData MDN
您的 axios 帖子似乎与您的路由器端点不匹配。axios 也是一个 Promise 库,因此您可以使用then
andcatch
来处理解决和拒绝操作。
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)
}
推荐阅读
- scala - 从现有的 arraytype 列中创建单独的 Spark 数据框
- flutter - 在 PageView 中的 WheelEvent 上 Flutter Web “平滑滚动”
- api - 在 curl (和 Rested API 客户端)中工作,但在 Postman 中不工作?
- asynchronous - Verilog d触发器异步复位亚稳态
- cobol - 如何更新到最新的 cobol
- angular - 如何在Angular 9中正确格式化从UTC到本地日期时间的日期管道?
- aws-sts - 使用 DefaultCredentialsProvider 从配置文件访问 AWS 会话令牌
- jquery - 从索引数据库获取 row().data() 时出错
- html - 如何使用 CSS 来创建具有此 HTML 布局的剔除(透明)文本?
- azure - 有没有办法在 Azure Kubernetes 的 AKS 节点上安装内核模块?