FastAPI 和 MongoDB 实现请求头参数处理的示例,并在 React 中进行渲染

FastAPI 和 MongoDB 后端

  1. 安装必要的库
    安装 FastAPI、Uvicorn、Motor(用于 MongoDB 的异步驱动)和 Pydantic(用于数据验证)。

    pip install fastapi uvicorn motor pydantic
    
  2. 创建 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, List
    
    app = FastAPI()
    
    # MongoDB 连接
    client = AsyncIOMotorClient("mongodb://localhost:27017")
    db = client["blogdb"]
    collection = db["blogs"]
    
    # 定义博客模型
    class Blog(BaseModel):
        title: str
        content: str
        author: str
        created_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 前端

  1. 创建 React 应用
    如果你还没有创建一个 React 应用,可以使用 Create React App 来快速创建一个。

    npx create-react-app my-react-app
    cd my-react-app
    npm start
    
  2. 修改 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>
              <input
                type="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;
    
  3. 添加样式
    为了使博客卡片看起来更好,可以在 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,你应该能看到通过请求头参数获取的博客列表。

注意事项

  1. 跨域问题
    如果你在开发环境中遇到跨域问题(CORS),可以在 FastAPI 应用中添加 CORS 中间件来解决。修改 main.py 文件:

    from fastapi.middleware.cors import CORSMiddleware
    
    app = FastAPI()
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
  2. 生产环境
    在生产环境中,你需要将 React 应用构建为静态文件,并将其部署到一个 Web 服务器上。同时,FastAPI 应用也需要部署到一个生产级的服务器上,如 Gunicorn 或 Uvicorn。

通过以上步骤,你可以在 React 中实现通过请求头参数获取 FastAPI 和 MongoDB 提供的数据,并动态渲染博客列表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源滚滚编程

创业不易,请打赏支持我一点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值