x-movie/src/components/LoginForm.jsx

100 lines
2.7 KiB
React
Raw Normal View History

2023-07-08 19:00:29 +00:00
// LoginForm.js
import React, { useContext, useState } from 'react';
import axios from 'axios';
2023-07-08 21:58:33 +00:00
import ConfigContext from '../Config';
2023-07-08 19:00:29 +00:00
import { useNavigate } from 'react-router-dom';
import {
Box,
Button,
Container,
Grid,
TextField,
Typography,
} from '@mui/material';
function LoginForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const config = useContext(ConfigContext);
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
2024-06-12 04:51:12 +00:00
const response = await axios.post(`${window.location.origin}/api/login`, new URLSearchParams({
2023-07-08 19:00:29 +00:00
username,
password,
}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
localStorage.setItem('token', response.data.token);
// 如果存在之前的页面路径,则返回,否则跳转到首页
const previousLocation = sessionStorage.getItem('previousLocation');
if (previousLocation) {
sessionStorage.removeItem('previousLocation');
navigate(previousLocation);
} else {
navigate('/');
}
} catch (error) {
setError('Invalid username or password');
}
};
return (
<Container maxWidth="xs">
<Box sx={{ marginTop: 8, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<Typography component="h1" variant="h5">
登录
</Typography>
{error && (
<Typography color="error" sx={{ marginTop: 1 }}>
{error}
</Typography>
)}
<Box component="form" onSubmit={handleSubmit} sx={{ width: '100%', marginTop: 3 }}>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
required
fullWidth
id="username"
label="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
id="password"
label="Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
sx={{ marginTop: 3 }}
>
Login
</Button>
</Box>
</Box>
</Container>
);
}
export default LoginForm;