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

Azure静态Web应用调用App API时的CORS问题求助

解决Azure静态Web应用中Vue3+FastAPI的CORS重定向问题

核心问题分析

当前端请求/api时被重定向到azurewebsites.net域名,本质是Azure静态Web应用的API路由映射未正确生效,导致请求未直接转发到绑定的FastAPI后端,反而跳转到了后端的原始部署域名,触发跨域拦截。


具体解决思路

1. 修正Azure静态Web应用的路由配置

在前端项目根目录创建或修改staticwebapp.config.json文件,确保API路径被正确代理到后端:

{
  "routes": [
    {
      "route": "/api/*",
      "backend": {
        "resourceId": "/api",
        "entryPoint": "/api"
      }
    },
    {
      "route": "/*",
      "serve": "/index.html",
      "statusCode": 200
    }
  ],
  "navigationFallback": {
    "rewrite": "/index.html",
    "exclude": ["/api/*"]
  }
}

该配置会将所有/api开头的请求直接转发到绑定的FastAPI后端,避免重定向到原始azurewebsites.net地址。

2. 确保FastAPI正确配置CORS中间件

即使路由问题解决,也要保证FastAPI允许前端域名的跨域请求,在FastAPI主文件中添加:

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

app = FastAPI()

# 替换为你的静态Web应用域名
origins = [
    "https://xxxxxxxxxxx-xxxxxxxx.3.azurestaticapps.net",
]

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

@app.get("/api")
async def root():
    return {"message": "Hello World"}

测试阶段可暂时将allow_origins设为["*"]放宽限制,但生产环境务必指定具体域名。

3. 检查前端Axios请求的路径配置

确保前端Axios使用正确的相对路径,若Vue项目配置了baseURL,确认其值为""或"/",避免强制跳转到其他域名:

import axios from 'axios'

const instance = axios.create({
  baseURL: '', // 保持为空或"/",使用当前域名的相对路径
})

// 请求示例
const resp = await instance.get("/api")

4. 验证Azure静态Web应用的后端绑定

登录Azure门户,进入你的静态Web应用,在左侧菜单API选项中,确认后端已正确绑定,且API路由前缀设置为/api。若绑定的是Azure Functions或其他资源,需确认其部署状态正常,无路径配置冲突。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:10:02