FastAPI+MongoDB+React实现查询博客详情功能

发布于:2025-05-15 ⋅ 阅读:(20) ⋅ 点赞:(0)

第一部分:FastAPI 和 MongoDB 后端

确保你的 FastAPI 应用已经配置好,并且 MongoDB 数据库已经运行。以下是完整的后端代码:

# main.py
from fastapi import FastAPI, HTTPException, Depends
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import BaseModel
from bson import ObjectId
from typing import Optional
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 允许所有来源访问
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# MongoDB 连接
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client["blogdb"]
collection = db["blogs"]

# 定义博客模型
class Blog(BaseModel):
    title: str
    content: str
    author: str
    created_at: str

# 创建一个博客
@app.post("/blogs/")
async def create_blog(blog: Blog):
    result = await collection.insert_one(blog.dict())
    return {
   "_id": str(result.inserted_id)}

# 获取所有博客
@app.get("/blogs/")
async def get_blogs():
    blogs = await collection.find().to_list(length=100)
    return [{
   "_id": str(blog["_id"]), **blog} for blog in blogs]

# 通过路径参数获取单个博客
@app.get("/blogs/{blog_id}")
async def get_blog(blog_id: str):
    blog = await collection.find_one({
   "_id": ObjectId(blog_id)})
    if not blog:
        raise HTTPException(status_code=404, detail="Blog not found")
    

网站公告

今日签到

点亮在社区的每一天
去签到