如何将FormData转换为Object然后JSON.stringify?

问题描述 投票:0回答:1

我如何将FormData转换为对象而不是JSON.stringify?我认为我的API中的值没有填充我的数据的原因是因为端点需要JSON数据。

handleSubmit:

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>
json reactjs form-data stringify
1个回答
0
投票

你可以使用formData.entries()方法遍历FormData中的所有条目并构造一个JSON对象,如下所示:

const json = {};
Array.from(formData.entries()).forEach(([key, value]) => {
  json[key] = value;
})

JSON.stringify(json)
© www.soinside.com 2019 - 2024. All rights reserved.