FastAPI与Next.js跨域问题:请求资源无Access-Control-Allow-Origin头
解决FastAPI与Next.js跨域CORS错误
问题场景
通过POST方法将localhost:3000上的Next.js前端数据提交至localhost:8000的FastAPI后端接口时,触发CORS错误:
Access to fetch at 'http://localhost:8000/api/report/create/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
当前已配置代码
FastAPI端CORS中间件配置
origins = [ "http://localhost:3000", #nextjs domain ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
Next.js端请求代码
try { const response = await fetch('http://localhost:8000/api/report/create/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }); if (response.ok) { // Handle successful response console.log('Case submitted successfully'); } else { // Handle error response console.error('Failed to submit case'); } } catch (error) { console.error('Error:', error); }
可行解决方案
确保CORS中间件优先加载:FastAPI中间件按添加顺序执行,必须将
CORSMiddleware放在所有路由和其他中间件之前添加。如果中间件添加顺序靠后,后续路由返回的错误响应(如404)可能不会带上CORS头。示例正确顺序:from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 先添加CORS中间件 origins = ["http://localhost:3000"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 再定义接口路由 @app.post("/api/report/create/") async def create_report(): return {"status": "ok"}验证接口路径匹配:检查FastAPI的接口路径与前端请求路径完全一致(包括末尾的斜杠)。如果路径不匹配,FastAPI返回404,此时CORS中间件可能未处理该响应,导致缺失头信息。
临时放宽origin测试:将
allow_origins改为["*"]测试跨域是否正常。如果问题解决,说明原origin配置存在细节错误(如协议不匹配、端口写错),修正后再改回具体origin。排查请求格式错误:确保
formData序列化后符合JSON格式要求。如果前端发送的JSON格式错误,FastAPI会返回422错误,此时可能未带上CORS头。可以先简化请求体为{"test": "data"}测试。检查代理或其他中间件干扰:如果FastAPI前端有反向代理(如Nginx),需确保代理服务器未移除CORS响应头,必要时在代理层补充跨域配置。
内容的提问来源于stack exchange,提问作者VictorM03
相关产品推荐
相关产品推荐

