Home > front end >  How can I request the value I get from the user to the backend api using react?
How can I request the value I get from the user to the backend api using react?

Time:05-01

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

CodePudding user response:

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

cors.allowed_from=http://localhost:3000
  • Related