Vercel部署FastAPI后端遇405 Method Not Allowed错误(本地正常)
首先明确:你遇到的405错误不是CORS问题——因为curl请求也失败,而curl不受浏览器CORS规则限制,说明请求根本没到达FastAPI的正确端点,或者Vercel的路由配置导致请求被错误处理。
核心问题分析
你的next.config.js里的rewrites配置在生产环境存在致命错误:
destination: process.env.NODE_ENV === "development" ? {NEXT_PUBLIC_LOCALHOST_URL} + "/:path*" : "/",
生产环境下所有请求都被转发到NextJS的根路径/,而不是FastAPI后端。NextJS的页面路由不处理POST/API请求,所以直接返回405。
另外,你模板字符串的写法错误:{NEXT_PUBLIC_LOCALHOST_URL}应该改成${process.env.NEXT_PUBLIC_LOCALHOST_URL},否则本地环境可能也会出问题(你说本地正常,可能是实际代码里已经修正,但贴出来的代码有误)。
解决方案
1. 修正NextJS的Rewrites配置
根据你的部署方式选择对应配置:
情况A:前端和FastAPI部署在同一个Vercel项目
FastAPI作为Vercel Serverless函数,通常放在/api目录下(比如/api/main.py),修改rewrites让API请求转发到FastAPI:
/** @type {import('next').NextConfig} */ const nextConfig = { rewrites: async () => { return [ { source: "/api/:path*", // 只转发API路径,避免影响前端页面 destination: process.env.NODE_ENV === "development" ? `${process.env.NEXT_PUBLIC_LOCALHOST_URL}/:path*` // 本地转发到FastAPI端口 : "/api/:path*", // 生产环境转发到同项目下的FastAPI函数 } ]; }, async headers() { return [ { source: "/api/:path*", // 只给API路径加CORS头,没必要全局加 headers: [ { key: "Access-Control-Allow-Credentials", value: "true" }, { key: "Access-Control-Allow-Origin", value: "*" }, { key: "Access-Control-Allow-Methods", value: "*" }, { key: "Access-Control-Allow-Headers", value: "*" }, ] } ] } }; module.exports = nextConfig;
情况B:前端和FastAPI部署在不同Vercel项目
直接把生产环境的destination改成FastAPI项目的Vercel域名:
destination: process.env.NODE_ENV === "development" ? `${process.env.NEXT_PUBLIC_LOCALHOST_URL}/:path*` : "https://your-fastapi-backend.vercel.app/:path*", // 替换成你的后端域名
2. 配置Vercel识别FastAPI函数(同项目部署时需要)
在项目根目录创建vercel.json,指定Python runtime和路由规则:
{ "buildCommand": "npm run build", "functions": { "api/main.py": { "runtime": "@vercel/python@3.10" // 匹配你的Python版本 } }, "routes": [ { "src": "/api/(.*)", "dest": "/api/main.py/$1" // 把/api/*请求转发到FastAPI入口 }, { "src": "/(.*)", "dest": "/$1" // 其他请求交给NextJS处理 } ] }
3. 确认FastAPI路由前缀
检查你的路由文件(比如text.router)是否设置了正确的前缀,比如:
# api/v1/endpoints/text.py from fastapi import APIRouter router = APIRouter(prefix="/text") # 确保前缀正确,前端请求路径要匹配 @router.post("/process") async def process_text(): # ...
前端请求路径应该是/api/text/process(对应同项目部署的情况)。
4. 验证部署
部署后用curl测试FastAPI端点:
curl -X POST https://your-vercel-project.vercel.app/api/text/process -d "test=data"
如果返回正常,说明路由配置正确,再测试前端请求。
内容的提问来源于stack exchange,提问作者theGreenCabbage

