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

Angular代理配置路由异常:调用.NET Web API返回404错误

问题诊断与解决方案

核心问题:代理配置的target路径错误

你的proxy.conf.js中target设置为https://localhost:7265/test,这会导致Angular代理将http://localhost:4200/test转发到https://localhost:7265/test/test(把匹配的/test追加到target路径后),而你的API实际有效路径是https://localhost:7265/test,因此请求会返回404。

修正步骤

  1. 修改proxy.conf.js的target为API根地址:
const PROXY_CONFIG = [
  {
    context: ["/test"],
    target: "https://localhost:7265", // 移除末尾的/test
    secure: true,
    logLevel: "debug",
    changeOrigin: true // 新增该配置,解决跨域请求时的主机头匹配问题
  }
];

module.exports = PROXY_CONFIG;
  • changeOrigin: true:当目标服务器主机头与本地开发服务器不一致时,该配置会将请求的主机头替换为target的主机,避免部分服务器的验证拦截。
  1. 重启Angular开发服务器:
    修改代理配置后必须重启ng serve,否则新配置不会生效,这也是代理日志未输出的常见原因。

  2. 确认调用代码无需修改:
    你的组件API调用代码http.get<WeatherForecast[]>('/test')是正确的,保持原样即可。

额外排查点

  • 检查angular.json中serve的options里proxyConfig路径是否与实际文件位置一致(你的配置src/proxy.conf.js如果文件确实在src目录下则没问题)。
  • 再次验证.NET API的/test端点正常运行,确保手动访问https://localhost:7265/test能返回预期数据。

修改完成后,代理会将http://localhost:4200/test正确转发到https://localhost:7265/test,即可正常获取API数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:07:39