最近开发了一个React18的后台管理系统,登录界面如下:
如果登录成功了则提示并跳转到首页:
点击注销按钮则提示退出系统成功:
没有登录就访问首页则提示请先登录。
这些功能是怎么实现的呢?
先看看登录功能使用FastAPI是怎么开发的。
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class LoginSchema(BaseModel):
username: str
password: str
@app.post("/login")
async def login(user: LoginSchema):
if user.username == "admin" and user.password == "123456":
return {"token": "xxx"}
raise HTTPException(400, "用户名或密码错误")
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=8888)
再来看看登录功能的前端代码是怎么写的:
import "./login.css"
import {Button, Checkbox, Form, Input, message} from 'antd';
import req from "../utils/request.js"
import {useNavigate} from "react-router-dom";
import storage from "../utils/storage.js";
function Login() {
const navigate = useNavigate();
// 点击登录
const onFinish = (values) => {
const data = {
username: values.username,
password: values.password,
}
req.post("/login", data).then(res => {
message.success("登录成功");
storage.set("token", res.token)
navigate("/")
}).catch(err => {
console.log("登录失败", err)
})
};
return <div className="login">
<div className="login-form">
<Form
name="basic"
onFinish={onFinish}
>
<Form.Item
label="账号"
name="username"
rules={[
{
required: true,
message: '账号不能为空',
},
]}
>
<Input/>
</Form.Item>
<Form.Item
label="密码"
name="password"
rules={[
{
required: true,
message: '密码不能为空',
},
]}
>
<Input.Password/>
</Form.Item>
<Form.Item
name="remember"
valuePropName="checked"
style={{marginLeft: '50px'}}
>
<Checkbox>记住我</Checkbox>
</Form.Item>
<Form.Item style={{marginLeft: '50px'}}>
<Button type="primary" htmlType="submit">
立即登录
</Button>
</Form.Item>
</Form>
</div>
</div>
}
export default Login
首页的代码则相对比较简单:
import {useEffect} from "react";
import req from "../utils/request"
import money from "../utils/money"
import date from "../utils/date"
import {useNavigate} from "react-router-dom";
import storage from "../utils/storage.js";
import {message} from "antd";
function Index() {
const navigate = useNavigate();
useEffect(() => {
if (!storage.get("token")) {
message.error("请先登录!")
navigate("/login")
}
}, [])
useEffect(() => {
req.get("/").then(resp => {
console.log("xxx", resp)
}).catch(err => {
console.log("错误了", err)
})
}, [])
// 用户注销
const logout = () => {
storage.delete("token")
navigate("/login")
message.success("退出系统成功!")
}
return (
<div className="container">
<h1>首页</h1>
<h3>格式化金额:{money.formatYuan(333444555)}</h3>
<h3>格式化日期:{date.format()}</h3>
<button onClick={logout}>注销</button>
</div>
)
}
export default Index
当然,想要实现完整的功能肯定远不止这些代码,这里录制了完整的视频教程如下。
如果你想要完整的代码,或者完整的视频教程,或者一对一的私教课,欢迎留言或者私信。