FastAPI 和 MongoDB 后端
-
安装必要的库
安装 FastAPI、Uvicorn、Motor(用于 MongoDB 的异步驱动)和 Pydantic(用于数据验证)。pip install fastapi uvicorn motor pydantic
-
创建 FastAPI 应用
创建一个文件
main.py
,并在其中定义一个接口,该接口通过请求头参数获取博客文章的详细信息。# main.py from fastapi import FastAPI, Request, HTTPException from motor.motor_asyncio import AsyncIOMotorClient from pydantic import BaseModel from bson import ObjectId from typing import Optional, Listapp = FastAPI()# MongoDB 连接 client = AsyncIOMotorClient("mongodb://localhost:27017") db = client["blogdb"] collection = db["blogs"]# 定义博客模型 class Blog(BaseModel):title: strcontent: strauthor: strcreated_at: str# 写入100条测试数据 async def create_test_data():for i in range(100):blog = Blog(title=f"测试博客 {i+1}",content=f"这是第 {i+1} 篇博客的内容",author=f"作者 {i+1}",created_at="2025-05-10 12:33:33")await collection.insert_one(blog.dict())# 初始化时创建测试数据 @app.on_event("startup") async def startup_event():await create_test_data()# 通过请求头参数获取博客 @app.get("/blogs/") async def get_blogs(request: Request):# 从请求头中获取参数api_key = request.headers.get("X-API-Key")if not api_key or api_key != "your_api_key":raise HTTPException(status_code=401, detail="Invalid API Key")blogs = await collection.find().to_list(length=100)return [{"_id": str(blog["_id"]), **blog} for blog in blogs]
React 前端
-
创建 React 应用
如果你还没有创建一个 React 应用,可以使用 Create React App 来快速创建一个。npx create-react-app my-react-app cd my-react-app npm start
-
修改
App.js
文件
在App.js
文件中,我们将实现通过请求头参数获取博客数据,并动态渲染博客列表。import React, { useState, useEffect } from 'react'; import './App.css';function App() {const [blogs, setBlogs] = useState([]);const [apiKey, setApiKey] = useState('your_api_key');useEffect(() => {fetchBlogs();}, [apiKey]);const fetchBlogs = () => {fetch('http://127.0.0.1:8000/blogs/', {headers: {'X-API-Key': apiKey}}).then(response => {if (!response.ok) {throw new Error('Request failed');}return response.json();}).then(data => setBlogs(data)).catch(error => console.error('Error fetching blogs:', error));};return (<div className="App"><header className="App-header"><h1>博客列表</h1><div><inputtype="text"value={apiKey}onChange={(e) => setApiKey(e.target.value)}placeholder="API Key"/><button onClick={fetchBlogs}>获取博客</button></div><div>{blogs.map(blog => (<div key={blog._id} className="blog-card"><h2>{blog.title}</h2><p>{blog.content}</p><p>作者: {blog.author}</p><p>创建时间: {blog.created_at}</p></div>))}</div></header></div>); }export default App;
-
添加样式
为了使博客卡片看起来更好,可以在App.css
文件中添加一些样式。.App {text-align: center; }.App-header {background-color: #282c34;min-height: 100vh;display: flex;flex-direction: column;align-items: center;justify-content: center;font-size: calc(10px + 2vmin);color: white; }.blog-card {background-color: #333;padding: 20px;margin: 10px 0;border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); }.blog-card h2 {margin-top: 0; }.blog-card p {margin: 10px 0; }input {margin: 10px 0;padding: 8px;border-radius: 4px;border: 1px solid #ccc; }button {padding: 8px 16px;background-color: #61dafb;border: none;border-radius: 4px;cursor: pointer; }button:hover {background-color: #007bff; }
运行 React 应用
确保你的 React 应用正在运行。如果你之前已经启动了 npm start
,那么它应该已经在运行了。
打开浏览器访问 http://localhost:3000
,你应该能看到通过请求头参数获取的博客列表。
注意事项
-
跨域问题
如果你在开发环境中遇到跨域问题(CORS),可以在 FastAPI 应用中添加 CORS 中间件来解决。修改main.py
文件:from fastapi.middleware.cors import CORSMiddlewareapp = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"], )
-
生产环境
在生产环境中,你需要将 React 应用构建为静态文件,并将其部署到一个 Web 服务器上。同时,FastAPI 应用也需要部署到一个生产级的服务器上,如 Gunicorn 或 Uvicorn。
通过以上步骤,你可以在 React 中实现通过请求头参数获取 FastAPI 和 MongoDB 提供的数据,并动态渲染博客列表。