[英]CORS blocking my backend server, how to fix? Using Springboot java as backend and react js as my front end
[英]How to pass values in front end react js to backend springboot
在前端,我創建了一個具有用戶名和密碼的登錄模塊,並在單擊登錄按鈕時登錄按鈕它應該將值傳遞給 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>
);
}
讓我知道如何將值添加到后端
您需要將帶有用戶名和密碼的請求發送到服務器或某些第三方 API 以進行身份驗證。
網上有很多教程,盡管它們的相關性取決於您支持的框架。 這是一個示例: https://www.cluemediator.com/login-app-create-login-form-in-reactjs-using-secure-rest-api 。
你快到了。 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
變量)。 所以它可能看起來像:
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 })
});
})();
}
此外,在生產前端應用程序(或其他任何地方)中記錄密碼時要小心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.