首先,我是react新手,我需要通过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",
${keyName})