0

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!

1 Answer 1

3

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

}
Sign up to request clarification or add additional context in comments.

11 Comments

Good answer, just to avoid confusion your request var is actually the request response value;
Thanks for the help but I am getting a "Cannot POST /list-certs" when I click the button. Am I missing something else? Do I need different paths for my GET and POST calls?
@tnoel999888: I think you need to stringify the data using JSON.stringify({domainInputValue})
@UmairAhmed does this go in the 'body:' declaration of the click() method?
@Dyo so should I change it to const response instead of const request?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.