[英]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在前端,我创建了一个具有用户名和密码的登录模块,并在单击登录按钮时登录按钮它应该将值传递给 spring 引导
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.您需要将带有用户名和密码的请求发送到服务器或某些第三方 API 以进行身份验证。
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 .这是一个示例: 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
). 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通过useState
的password
变量)。 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.).此外,在生产前端应用程序(或其他任何地方)中记录密码时要小心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.