Azure Static Web App部署后Vite代理失效引发CORS问题求助
解决Azure Static Web App部署后React SPA的CORS与代理失效问题
问题核心
你的Vite server.proxy配置仅在开发环境(vite dev)生效,生产构建后的静态文件部署到Azure SWA时,该代理逻辑不会被保留。直接请求外部API会触发浏览器CORS拦截,原因是外部API未配置允许你的SWA域名跨域访问。
解决方案:使用Azure SWA自带的路由代理配置
Azure Static Web App支持通过staticwebapp.config.json文件配置生产环境的路由与代理规则,替代Vite开发代理的功能。
1. 创建配置文件
在项目根目录(与package.json同级)新建staticwebapp.config.json文件,添加以下配置:
{ "routes": [ { "match": "/api/*", "rewrite": "/{rest}", "forwardTo": "https://externalAPI/{rest}", "allowedHeaders": ["accept", "token"] } ], "navigationFallback": { "rewrite": "/index.html", "exclude": ["*.{js,css,png,jpg,gif}"] } }
match: 匹配前端发起的/api开头的请求rewrite: 移除路径开头的/api(与你Vite配置里的rewrite逻辑一致)forwardTo: 将请求转发到外部API的对应路径allowedHeaders: 允许传递自定义请求头(比如你的token)
2. 恢复前端请求代码
改回开发环境的请求写法,不要直接写外部API地址:
return fetch(`/api/Session/MakeSession`, { headers: { accept: 'text/plain', token: res.accessToken }, }) .then((res) => { if (!res.ok) { throw new Error(`Failed to create session with status ${res.status}`); } return res.json(); }) .then((data) => { setUserData(data); }) .catch((error) => { console.error('Error fetching data:', error); });
3. 重新部署到Azure SWA
将包含staticwebapp.config.json的代码提交并重新部署,SWA会自动读取该配置并处理代理请求。此时请求通过SWA服务器转发到外部API,不会触发浏览器的CORS限制(因为发起请求的是SWA服务器,而非前端浏览器)。
关键说明
- Azure SWA的代理配置是服务器端转发,完全规避浏览器CORS机制
- 确保
staticwebapp.config.json放在项目根目录,部署时会被SWA自动识别 - SWA转发请求时会自动处理
Origin头,等效于Vite配置里的changeOrigin: true
内容的提问来源于stack exchange,提问作者swwjjj_ok
相关产品推荐
相关产品推荐

