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 提供的數據,并動態渲染博客列表。