You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React/JS中通过POST传递JSON数据且避免OPTIONS请求?

解决FastAPI后端接收JSON认证请求的正确方式

问题根源

  1. 设置Content-Type: application/json时出现OPTIONS请求是跨域预请求,报错是因为后端未配置CORS(跨域资源共享)规则,导致浏览器拦截了响应。
  2. 使用Content-Type: application/x-www-form-urlencoded并发送JSON.stringify(data)时,FastAPI无法解析是因为该类型下,后端默认会把数据按表单格式处理,而非解析JSON字符串。

正确实现步骤

1. 前端正确发送JSON请求

保持Content-Type: application/json头部,直接发送JSON字符串格式的请求体,示例代码:

const authData = { email: 'user@example.com', password: 'your_password' };
fetch('/auth/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(authData),
})
.then(res => res.json())
.catch(err => console.error('请求失败:', err));

2. 后端FastAPI配置CORS并接收JSON

FastAPI自带CORSMiddleware,只需在代码中添加配置即可处理跨域预请求,同时用Pydantic模型接收JSON数据:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

app = FastAPI()

# 配置允许的跨域源(替换为你的前端实际地址)
origins = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 定义JSON请求体的模型
class AuthRequest(BaseModel):
    email: str
    password: str

# 认证接口
@app.post("/auth/login")
async def handle_login(auth_info: AuthRequest):
    # 这里写你的认证逻辑
    return {"status": "success", "email": auth_info.email}

3. 方案说明

  • 前端正确设置请求头和请求体格式,完全匹配FastAPI接收JSON的要求。
  • 后端配置CORSMiddleware后,会自动响应OPTIONS预请求,返回合法的跨域头,浏览器不再拦截后续的POST请求。

额外提醒

  • 开发阶段前后端通常用不同端口,必然触发跨域预请求,必须配置CORS;若部署在同一域名下则无需此步骤。
  • 不要混用表单类型头和JSON字符串,FastAPI接收表单数据需要用Form类,和JSON的处理逻辑完全不同。

内容的提问来源于stack exchange,提问作者Liza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 14:47:06