【发布时间】:2019-12-06 15:31:29
【问题描述】:
我正在尝试在我的 react 应用程序中发送 multipart/formdata。每次我使用 axios 访问 POST api 时,formdata 总是为空。我尝试转换为 JSON.stringify 和键值方法,但似乎没有任何效果。我确实将标题设置为'Content-Type': 'multipart/form-data'
postList = (e) => {
e.preventDefault();
var postParams;
if(this.state.message && this.state.parent){
postParams = {
message: this.state.message,
chat_m_id: this.state.parent,
depth: (1).toString(),
msg_icon: this.state.msg_icon.name
}
}
else{
postParams = {
message: this.state.message,
chat_m_id: (0).toString(),
depth: (0).toString(),
msg_icon: this.state.msg_icon.name
}
}
console.log(postParams);
let bodyFormData = new FormData();
//approach-one
bodyFormData.append('data',postParams);
//approach-one
// bodyFormData.append('data',JSON.stringify(postParams));
//approach-three
// for (let [key, value] of Object.entries(postParams)) {
// bodyFormData.append(`'${key}'`, JSON.stringify(`${value}`));
// }
console.log(bodyFormData) //this is always empty
axios.post(GlobalVar.BASE_URL+'api/msgtemplate/create', bodyFormData, {headers: GlobalVar.headersFormData})
.then(res => {
console.log(res)
this.props.history.push('/messages')
})
.catch(err => console.log(err.res));
}
我已经花了几个小时,请帮助解决它。
【问题讨论】: