简体   繁体   中英

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

Disclaimer: I am new to React and Nodejs and have of course looked at all the current similar posts but none of them were able to help me fully so please don't mark as duplicate.

In my Nodejs index.js I have:

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!')
});

And in my React App.js I have:

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>
      .
      .
      .
}

How do I send the data in my input field domain-input to my back-end when the button domain-button is clicked? I know something needs to go in the click() but I'm not sure what.
Any help is appreciated!

Your click function will look like it:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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