// LoginForm.js import React, { useContext, useState } from 'react'; import axios from 'axios'; import ConfigContext from '../Config'; 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 { const response = await axios.post(`${window.location.origin}/api/login`, new URLSearchParams({ 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 ( 登录 {error && ( {error} )} setUsername(e.target.value)} /> setPassword(e.target.value)} /> ); } export default LoginForm;