我将如何将我的FormData转换为对象而不是JSON.stringify?我认为我在 API 中的值没有填充我的数据的一个原因是因为端点需要 JSON 数据。
句柄提交:
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
fetch('http://localhost:8080/seniorproject/addUser', {
method: 'POST',
body: data,
});
console.log(data);
}
形式:
<form onSubmit={this.handleSubmit}>
<label htmlFor="First Name">Enter First Name</label>
<input id="firstName" name="firstName" type="text" />
<label htmlFor="Last Name">Enter your Last Name</label>
<input id="lastName" name="lastName" type="lastName" />
<label htmlFor="studentID">Enter your student id</label>
<input id="studentID" name="studentID" type="text" />
<label htmlFor="Email">Enter your email</label>
<input id="email" name="email" type="text" />
<label htmlFor="Password">Enter your password</label>
<input id="password" name="password" type="text" />
<button>Send data!</button>
</form>
您可以使用
formData.entries()
方法遍历FormData
中的所有条目并构造一个 JSON 对象,如下所示:
const json = {};
Array.from(formData.entries()).forEach(([key, value]) => {
json[key] = value;
})
JSON.stringify(json)