首页 > 解决方案 > 为什么我的 POST 请求不会更新我的 data.json 文件?

问题描述

因此,用户应该能够填写表单并提交,这应该使用新评论更新本地 JSON 服务器。目前它不工作。我正在使用我使用 json-server --watch db.json 检查的正确端口。我做错了什么?

class CommentForm extends Component {
  handleSubmit = (e) => {
    e.preventDefault();
    console.log("submitted");

    const body = e.target.body.value;

    fetch("http://localhost:3000/comments", {
      method: "POST",
      body: JSON.stringify(body)
    }).then((response) => {
      console.log(response);
      return response.json(); // do something with response JSON
    });
  };

  render() {
    return (
      <div>
        <h1>What is your favorite breed?</h1>
        <form onSubmit={this.handleSubmit}>
          <label>Answer: </label>
          <br />
          <textarea type="text" name="body" />
          <br />
          <input type="submit" />
        </form>
      </div>
    );
  }
}

export default CommentForm
{
    "comments": [
      { 
        "text": "Australian Shepherd!"
      },
      { 
        "text": "German Shepherd!"
      },
      { 
        "text": "Mutts all the way"
      },
      { 
        "text": "Chihuahua"
      },
      { 
        "text": "Great Pyrenees rock!!!"
      }
    ]
  }

标签: jsonreactjsfetchjsx

解决方案


推荐阅读