Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I request the value I get from the user to the backend api using react?

I wrote a simple api using spring boot. For example, when I send http://localhost:8080/rps?choise=rock request, the response is "You choose Rock and CPU choose Paper ,You Lose!" it turns.
enter image description here

I created a simple interface using ReactJs, there are 3 buttons on the screen, rock, paper and scissors. When the user clicks on one of them, I want to send a request to the API and show the response value on the screen. I found that the request was not sent when I clicked on the buttons. How can I request the value I get from the user to the backend api and how can I show the response value on the screen?

import './App.css';
import React, {useState, useEffect} from 'react';
import RockImage from "./resources/rock.jpeg"
import PaperImage from "./resources/paper.jpeg"
import ScissorsImage from "./resources/scissors.jpeg"
import GameBanner from "./resources/banner.png"
import axios from 'axios';


function App() {

  const [userChoiceToWord,setUserChoiceToWord] = useState();
  const [response,setResponse] = useState();

  useEffect(function(){
    onSubmit()
  },[userChoiceToWord])

  async function onSubmit() {
    try {
      const response = await axios.post('http://localhost:8080/rps?choise=', userChoiceToWord);
      setResponse(response)
      alert(response);
    } catch (err) {
      setResponse(err)
      alert(err);
    }
  }

  function setRock(){
    setUserChoiceToWord("Rock");
  }

  function setPaper(){
    setUserChoiceToWord("Paper");
  }

  function setScissors(){
    setUserChoiceToWord("Scissors");
  }

  return (
    <div className="App">
      <img src={GameBanner} />
      <br></br>
      <button><img src={RockImage} alt="rock" onClick={setRock}/></button>
      <button><img src={PaperImage} alt="paper" onClick={setPaper} /></button>
      <button><img src={ScissorsImage} alt="scissors" onClick={setScissors} /></button>
    </div>
  );
}

export default App;

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your springboot application.properties update the below config and try :

cors.allowed_from=http://localhost:3000
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading