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

React与ASP.NET Core跨域报错求助:Access-Control-Allow-Origin 403

解决React + ASP.NET Core跨域(Access-Control-Allow-Origin)问题

快速修复:修正CORS允许源

从报错信息能看到,实际请求的Origin是http://www.example.com,但你的ASP.NET Core后端CORS配置里只允许了http://www.x.com,这直接导致了403跨域错误。

修改后端CORS配置,将允许的Origin替换为前端实际访问的域名:

builder.Services.AddCors(options => options.AddDefaultPolicy(
    policy => policy
    // 替换成你前端的实际域名,比如报错里的http://www.example.com
    .WithOrigins("http://www.example.com")
    .AllowAnyHeader()
    .AllowAnyMethod()
));
app.UseCors();

如果有多个环境需要支持(比如开发环境的localhost),可以传入数组:

.WithOrigins("http://www.example.com", "http://localhost:3000")

更优方案:用IIS反向代理彻底避免跨域

因为前端和后端部署在同一服务器,没必要直接请求localhost:5000,通过IIS反向代理将前端的/api路径转发到后端服务,就能彻底消除跨域问题(同一域名下请求无跨域限制)。

步骤如下:

  1. 修改前端API地址
    将.env文件中的VITE_API改为相对路径:

    VITE_API=/api
    

    前端axios请求会自动使用当前域名的/api路径,无需硬编码后端地址。

  2. 更新web.config添加反向代理规则
    在原有的rewrite规则前新增一条代理规则,把/api开头的请求转发到后端的localhost:5000/api:

    <?xml version="1.0"?>
    <configuration>
     <system.webServer>
     <rewrite>
     <rules>
       <!-- 新增:将/api请求转发到后端服务 -->
       <rule name="Proxy to Backend" stopProcessing="true">
         <match url="^api/(.*)" />
         <action type="Rewrite" url="http://localhost:5000/api/{R:1}" />
       </rule>
       <!-- 原有React路由规则 -->
       <rule name="React Routes" stopProcessing="true">
         <match url=".*" />
         <conditions logicalGrouping="MatchAll">
           <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
           <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
           <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
         </conditions>
         <action type="Rewrite" url="/" />
       </rule>
     </rules>
     </rewrite>
     </system.webServer>
    </configuration>
    
  3. 后端配置调整(可选)
    此时请求来自同一域名,CORS配置可以简化甚至移除,若保留则可以限制为当前域名进一步提高安全性。

额外检查项

  • 确认后端服务localhost:5000在服务器上正常运行,且服务器本地能访问该地址(可以用curl或浏览器在服务器上测试)
  • 清除浏览器缓存后再测试,避免旧的CORS缓存干扰
  • 如果使用Windows身份验证,需要在后端CORS配置中添加.AllowCredentials(),同时前端axios请求开启withCredentials: true:
    axios.get(`${import.meta.env.VITE_API}/supports`, { withCredentials: true })
    

内容的提问来源于stack exchange,提问作者Omar Dak Elbab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:42:45