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

如何解决iron-ajax响应延迟及跨域访问被拒问题

解决AJAX跨域(CORS)问题的可行方案

我来帮你搞定这个跨域问题——这个错误是典型的CORS(跨源资源共享)限制导致的,毕竟你的前端部署在app.domain.com,API却在api.domain.com,属于不同子域名,浏览器的同源策略会拦住这类跨域请求。你提到的“超时后报错”,大概率是浏览器发送了OPTIONS预检请求,但API服务器没正确响应,导致浏览器等待超时触发的错误。下面是几个经过验证的可行解决办法:

  • 直接在API服务器(IIS)配置CORS响应头
    这是最直接的方案,你需要在api.domain.com的IIS站点中添加CORS相关响应头,明确允许https://app.domain.com的访问:

    1. 如果你已经安装了IIS的CORS模块(可通过Web平台安装器安装),直接在站点的CORS配置面板中,添加允许的源为https://app.domain.com,同时勾选你需要的HTTP方法(比如GET、POST等)和自定义请求头。
    2. 若未安装CORS模块,也可以用URL Rewrite模块手动添加响应头,在API站点的web.config中插入以下配置:
      <system.webServer>
        <rewrite>
          <outboundRules>
            <!-- 允许指定源的跨域请求 -->
            <rule name="Add CORS Origin Header">
              <match serverVariable="RESPONSE_Access-Control-Allow-Origin" pattern=".*" />
              <conditions>
                <add input="{HTTP_ORIGIN}" pattern="^https://app\.domain\.com$" />
              </conditions>
              <action type="Rewrite" value="{HTTP_ORIGIN}" />
            </rule>
            <!-- 处理OPTIONS预检请求的允许方法 -->
            <rule name="Add CORS Allow Methods" preCondition="IsOPTIONSRequest">
              <match serverVariable="RESPONSE_Access-Control-Allow-Methods" pattern=".*" />
              <action type="Rewrite" value="GET,POST,PUT,DELETE,OPTIONS" />
            </rule>
            <!-- 处理OPTIONS预检请求的允许头 -->
            <rule name="Add CORS Allow Headers" preCondition="IsOPTIONSRequest">
              <match serverVariable="RESPONSE_Access-Control-Allow-Headers" pattern=".*" />
              <action type="Rewrite" value="Content-Type,Authorization" />
            </rule>
            <preConditions>
              <preCondition name="IsOPTIONSRequest">
                <add input="{REQUEST_METHOD}" pattern="OPTIONS" />
              </preCondition>
            </preConditions>
          </outboundRules>
        </rewrite>
      </system.webServer>
      
      配置完成后,API会对来自app.domain.com的请求返回合法的CORS头,浏览器就不会拦截响应了。
  • 在前端所在的IIS站点配置反向代理
    另一种思路是彻底避免跨域请求:让前端直接请求同域名的路径,再通过IIS反向代理转发到api.domain.com:

    1. 先安装IIS的Application Request Routing(ARR)模块和URL Rewrite模块。
    2. 在app.domain.com的web.config中添加反向代理规则:
      <system.webServer>
        <rewrite>
          <rules>
            <rule name="Proxy to API Server" stopProcessing="true">
              <!-- 匹配前端发起的/api开头的请求 -->
              <match url="^api/(.*)" />
              <!-- 转发到API服务器的对应路径 -->
              <action type="Rewrite" url="https://api.domain.com/{R:1}" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
      
      之后前端的AJAX请求只需改成/api/endpoint,不用再直接请求https://api.domain.com/endpoint,自然就不会触发跨域检查了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:35:22