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

Next.js启用--experimental-https后与FastAPI交互的CORS及重定向问题

本地HTTPS环境下Next.js与FastAPI通信问题解决

问题背景

因测试需求需在本地使用HTTPS,当前通过--experimental-https启动Next.js前端,使用Axios向FastAPI后端的http://localhost:3100/retrieve-prices和http://localhost:3100/get-subscription发起GET请求,出现通信异常。

错误现象

浏览器抛出两类错误:

  • GET https://localhost:3100/retrieve-prices net::ERR_CONNECTION_REFUSED
  • Access to XMLHttpRequest at 'http://localhost:3100/get-subscription' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

注:两个请求的唯一区别是get-subscription携带了带Bearer令牌的Authorization请求头。

网络请求详情

retrieve-prices请求

第一条请求记录:

Request URL: http://localhost:3100/retrieve-prices
Request Method: GET
Status Code: 307 Internal Redirect
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://localhost:3000
Cross-Origin-Resource-Policy: Cross-Origin
Location: https://localhost:3100/retrieve-prices
Non-Authoritative-Reason: HSTS

第二条请求记录:

Request URL: https://localhost:3100/retrieve-prices
Referrer Policy: strict-origin-when-cross-origin

get-subscription请求

仅显示:

Request URL: http://localhost:3100/get-subscription
Referrer Policy: strict-origin-when-cross-origin

现有FastAPI配置

已配置CORS并移除相关中间件,但问题未解决:

app = FastAPI(lifespan=lifespan)

origins = ["http://localhost:3000", "https://localhost:3000"]

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

app.remove_middleware(HTTPSRedirectMiddleware)
app.remove_middleware(TrustedHostMiddleware)

解决方案

1. 让FastAPI启动HTTPS服务

浏览器因HSTS策略自动将HTTP请求重定向到HTTPS,但FastAPI默认使用HTTP,导致连接拒绝。开发环境可快速生成自签证书并启动HTTPS服务:

  • 生成自签证书(需安装openssl):
    openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
    
  • 启动FastAPI时指定证书:
    uvicorn main:app --host 0.0.0.0 --port 3100 --ssl-keyfile=key.pem --ssl-certfile=cert.pem
    

2. 修改Axios请求地址为HTTPS

将所有请求的URL从http://localhost:3100改为https://localhost:3100,避免浏览器触发自动重定向,进而消除预请求的CORS错误。

3. 信任自签证书

Next.js和FastAPI的自签证书会被浏览器标记为不安全,需手动信任:

  • 访问https://localhost:3000和https://localhost:3100,在浏览器提示中选择信任该证书。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:43:23