简体   繁体   中英

How to pass values in front end react js to backend springboot

In the front end, I have created a login module that has a user name and password, and login button it on clicking login button it should pass the values to spring boot

export default function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  function validateForm() {
    return username.length > 0 && password.length > 0;
  }

  function handleSubmit(event) {
    event.preventDefault();
  }

  function LoginUser(){
    console.log(username, password);
  }

  return (
    <div className="Login">
      <Form onSubmit={handleSubmit}>
        <Form.Group size="lg" controlId="username">
          <Form.Label>Username</Form.Label>
          <Form.Control
            type="username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
          />
        </Form.Group>
        <Form.Group size="lg" controlId="password">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </Form.Group>
        <Button block size="lg" type="submit" onClick={LoginUser} disabled={!validateForm()} >
          Login
        </Button>
      </Form>
    </div>
  );
}

Let me know how to add the values to the backend

You will need to send the request with the username and password either to a server or some third party API to authenticate.

There are plenty of tutorials online, though their relevance will depend on your backed framework. Here is an example: https://www.cluemediator.com/login-app-create-login-form-in-reactjs-using-secure-rest-api .

You're nearly there. You just need to add an actual RESTful API call ( POST , most likely) using React's built-in fetch API to the LoginUser() function, which is already being called upon a user clicking the Button component (and should have access to username and password variables via useState ). So it might look something like:

function LoginUser() {
  console.log(username, password);
  (async () => {
    await fetch('http://path-to-spring-boot-api/', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ 'username': username, 'password': password })
    });
  })();
}

Also, be careful with logging passwords in production front-end applications (or anywhere else.).

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