reactjs - 如何通过反应传递数据,包括邮递员中表单数据类型的文件?
问题描述
首先,我是新手,我需要通过 API 将数据从前端传递到后端。数据是来自 POSTMAN 的表单数据类型。下图显示了 POSTMAN 中的 API 工作
我在这里使用表单数据作为我的 api 数据。
所以这里的问题。由于这是我第一次处理将文件传递给表单数据的问题。下面的代码是我所做的:
constructor (props){
super(props);
const supplier_id = parseInt(localStorage.getItem('id'));
this.state ={
supplier_id: supplier_id,
item_name:'',
item_shortDes: '',
item_longDes: '',
price: '',
terms_agreement: '',
Location: '',
selectedFile: null, // The item file which I need to pass to api.
redirect: false,
}
this.onChange = this.onChange.bind(this);
this.createItem = this.createItem.bind(this);
}
createItem(){
console.log(this.state)
fetch(`http://localhost:9000/api/item/submit`, { // callling the API here
method: 'post',
body: JSON.stringify(this.state)
}).then ((result) => {
let responseJSON = result;
console.log(responseJSON);
});
}
我在这里得到错误:
所以我相信这是因为我没有通过form-data
. 我对吗?我将如何处理这个?
解决方案
首先,您需要发送表单数据,您必须像自爆一样调用表单数据类。
formData = new FormData()
然后开始附加您的表单数据
formData.append("keyName",
${键名})
推荐阅读
- swiftui - SwiftUI:如何将字体颜色保持在顶部边缘区域?
- python - (python)标记在3-D坐标系相似区域内的点
- php - 重复使用相同的表单进行更新和创建,还是在 Laravel 中有更简单的方法?
- ruby - CSS 更改未显示 Ruby、Bootstrap
- javascript - 实现滚动锚定时元素“轻微抽搐”
- snowflake-cloud-data-platform - 雪花如何循环对象数组并将数据合并到相关表中而不将数组移动到临时表中?
- c# - 如何在 Entity Framework 6 中将 SQL 查询转换为 Linq?
- symfony - 在 Symfony5 中创建一个从一个小时开始执行多次的命令
- javascript - HTML、CSS 和 JavaScript 游戏中的背景图像不显示
- perl - 哈希参考中的 Perl 访问值