繁体   English   中英

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

[英]How to send data from React front-end to Nodejs Express back-end on button click

免责声明:我是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()需要添加一些内容,但我不确定。
任何帮助表示赞赏!

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM