【问题标题】:Unable to perform POST operation in React with fetch无法在 React 中使用 fetch 执行 POST 操作
【发布时间】:2020-11-21 11:22:10
【问题描述】:

我正在尝试使用 ReactJS 执行 POST 请求并使用 Spring-boot 在 Mongo 数据库中进行更新。在编译代码期间,我没有收到任何错误,但是在尝试执行 POST 操作时,我没有得到输出。当我刷新页面时,我在数据库中得到一个带有 ID 但没有名称的条目。

这是反应应用程序的代码:

async handleSubmit(event){
    event.preventDefault();
    const {item} = this.state;

    await fetch(`/person/new`, {
      method : 'POST',
      headers : {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body : JSON.stringify({item}),
    });
    
    this.props.history.push("/change");
  }

Spring-boot中POST的代码是:

public Integer Counter(){
    List<Person> p = pr.findAll();
    c = 1;
    while(pr.existsById(c)) {
        c++;
    }
    return c;
}

@PostMapping("/new")
public void insertPerson(@RequestBody Person person){
    Integer id = Counter();
    String name = person.getName();
    pr.save(new Person(id,name));
    c++;
}

这是我的网站在执行代码时的样子↓

How my site looks

请帮帮我。

PS:DELETE 操作虽然有效。

【问题讨论】:

  • 首先检查您的网络选项卡,因此请确保前端向后端发送正确格式的数据。

标签: reactjs spring-boot react-router reactstrap


【解决方案1】:

我认为这是你如何调用这个函数的问题。我建议像这样调用它:onClick = { async (e) =&gt; await { this.handleSubmit(e); } }

【讨论】:

    猜你喜欢
    • 2017-12-02
    • 2018-12-18
    • 2021-04-02
    • 2019-11-26
    • 2021-12-06
    • 2019-06-24
    • 2020-05-12
    • 1970-01-01
    • 2022-09-23
    相关资源
    最近更新 更多