简体   繁体   中英

How can I send text value of a button to the server in ReactJS + ExpressJS?

I'm having trouble sending button text value back to the server.

The code of the button in client-side:

{question.options?.map((option, index) =>
    <button key={index} className={styles.answer} onClick={() => guessHandling()}>{option}</button>)}

The code of the onClick guessHandling function in client-side:

const guessHandling = async (userGuess) => {
      const res = await axios.post('/api/guess', { userGuess });
        setStatusMessage(res.data.returnStatus);
};

The code in server-side:

app.post('/guess', (req, res) => {
  console.log(req.body.userGuess);   // <---- I RECIEVE "UNDEFINED" IN THE SERVER CONSOLE HERE. 
  res.send({
    returnStatus: "Guess Recieved"
  });
});

userGuess is undefined when I try to console.log it as seen above.

I also tried including.value, .innerText, .innerHTML... still does not work.

I tried using useState, but I do not know how to insert the button text into the state (which is the main problem of this question).

(Probably?) I'm missing something in the onClick functionality.. I would love to get some help on this problem.

As Elan Hamburger wrote in the comments, Solution is simple:

You didn't actually pass the value into your call to guessHandling. Try: onClick={() => guessHandling(option)}

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