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

Angular配置proxy后前端请求错误后端URL问题排查

问题核心原因

Angular 官方提供的 proxy.config.json 代理配置仅适用于本地开发时启动的 ng serve 内置开发服务器,生产环境执行 ng build 打包时,不会将代理规则编译到最终的静态产物中,因此部署到 IIS 后代理规则完全不生效,接口请求默认会打到当前前端站点的域名下。


两种可行解决方案

方案1:前端配置生产环境API地址(需后端开启CORS)

  • 第一步:修改 Angular 项目生产环境配置文件 src/environments/environment.prod.ts,新增后端地址配置:
export const environment = {
  production: true,
  // 新增生产环境后端基础地址
  apiBaseUrl: 'http://my.server.ip.address:190'
};
  • 第二步:调整全局接口调用逻辑,所有请求路径拼接环境变量中的基础地址,示例:
// 引入环境配置
import { environment } from 'src/environments/environment';

// 原来的接口调用写法
// this.http.post('/api/register', params)
// 调整后的写法
this.http.post(`${environment.apiBaseUrl}/api/register`, params)
  • 第三步:在后端 .NET Core Web API 项目中配置 CORS 规则,允许前端域名 mywebsite.com 的跨域请求。

方案2:IIS 配置反向代理(无需修改前端代码、无需开CORS)

该方案直接在前端站点的 IIS 中配置规则,把所有 /api 开头的请求转发到后端 190 端口:

  • 第一步:给 IIS 安装「Application Request Routing (ARR)」和「URL Rewrite」两个模块
  • 第二步:在 mywebsite.com 对应的 IIS 站点根目录下添加/修改 web.config 文件,配置如下规则:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <!-- API请求转发规则 -->
        <rule name="ForwardToBackendApi" stopProcessing="true">
          <match url="^api/(.*)" />
          <action type="Rewrite" url="http://my.server.ip.address:190/api/{R:1}" />
        </rule>
        <!-- Angular 路由刷新404修复规则 -->
        <rule name="AngularRouteFix" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

额外配置纠正

你在 angular.json 的 serve 节点下添加的生产环境代理配置没有任何作用,serve 节点的所有配置仅针对 ng serve 命令生效,ng build 命令不会读取该节点的配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 09:24:05