单击按钮如何将数据从React前端发送到Nodejs Express后端

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

免责声明:我是React和Nodejs的新手,当然查看了所有当前的类似文章,但是它们都无法完全帮助我,因此请不要将其标记为重复。

在我的Node.js index.js我有:

app.get('/list-certs', function (req, res) {
   fs.readFile("certs.json", 'utf8', function (err, data) {
       console.log( data );
       res.send( data );
   });
})

app.post('/list-certs', function (req, res) {
    res.send('POST request: ' + req.body.domain-input);
    console.log('post is working!')
});

在我的React App.js我有:

componentDidMount() {
  this.callApi()
    .then(res => {
      this.setState({
        json: res.map(x => x),
      })
    })
    .catch(err => console.log(err));
}


callApi = async () => {
  const response = await fetch('/list-certs');
  const body = await response.json();

  if (response.status !== 200) throw Error(body.message);
  return body;
};


handleChange(event) {
  this.setState({domainInputValue: event.target.value});
}


click() {
}


render() {
  return (
    <div className="App">

      <form action="http://127.0.0.1:8000/list-certs" className="add-cert-form" method="post">
        <h1>Add new domain</h1>
        <h5 className="domain-label">Name:</h5>
        <Input className="domain-input" value={this.state.domainInputValue} onChange={(e) => {this.handleChange(e)}}></Input>
        <Button onClick={this.click} className="domain-button" type='primary'>Add</Button>
      </form>
      .
      .
      .
}

单击按钮domain-button时,如何将输入字段domain-input的数据发送到后端? 我知道click()需要添加一些内容,但我不确定。
任何帮助表示赞赏!

node.js reactjs rest express post
1个回答
1
投票

您的点击功能将如下所示:

async click() {
    const { domainInputValue } = this.state;
    const request = await fetch('/echo/json', {
        headers: {
            'Content-type': 'application/json'
        },
        method: 'POST',
        body: { domainInputValue }
    });

}
© www.soinside.com 2019 - 2024. All rights reserved.