Files
react_jp_chat/src/pages/login/Login.jsx
T
2026-06-04 16:26:23 +09:00

48 lines
1.3 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {useState} from 'react';
import {useNavigate} from 'react-router-dom';
import './Login.css';
import axios from 'axios';
export default function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();
const handleSubmit = async e => {
e.preventDefault();
try {
const resp = await axios.post(
'https://api.rop.cc/auth',
{username, password},
{withCredentials: true}
);
console.log('接收到resp', resp);
// 假设后端返回 { token: 'xxxx' } 保留本地token
// localStorage.setItem('jwt', resp.data.token);
// localStorage.setItem('_uname', resp.data.username);
// 跳转到首页或登录前尝试访问的页面
navigate('/', {replace: true});
} catch (err) {
console.log(err)
alert(`[[Login failed]] error = ${err}`);
}
};
return (<form className="login" onSubmit={handleSubmit}>
<h2>Login</h2>
<input
value={username}
onChange={e => setUsername(e.target.value)}
placeholder="username"
/>
<input
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="password"
/>
<button type="submit">submit</button>
</form>);
}