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

Angular API代理路由通配符失效问题求助

代理配置添加通配符后失效的解决办法

问题说明

在proxy.conf.js中为路由添加通配符/*后,代理功能失效,请求未转发到目标API,返回404错误,错误信息如下:

HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: '未找到', url: 'http://localhost:4200/fi/ameribor', ok: false, …}

当context设为精确匹配的"/fi/ameribor"时一切正常,但使用"/fi/ameribor/*"时就会出现上述问题。当前相关代码如下:

当前代理配置

const PROXY_CONFIG = [
    {
      context: [
        "/fi/ameribor/*"
      ],
      target: "http://localhost:10000",
      secure: false,
      changeOrigin: true
    }
  ]
  
module.exports = PROXY_CONFIG;

对应的GET请求代码

getAmeriborRates(term:string, start:string, end:string):Observable<Rate[]>{

    let queryParams = new HttpParams()
      .set('Term', term)
      .set('Start', start)
      .set('End', end);

    console.log(queryParams.toString());

    return this.http.get<Rate[]>('/fi/ameribor');
    //return this.http.get<Rate[]>('/fi/ameribor', {params:queryParams});
}

问题原因

"/fi/ameribor/*"的通配符模式仅匹配带有子路径的请求(比如/fi/ameribor/123),但你的请求是精确路径/fi/ameribor(无任何子路径),因此无法匹配到代理规则,请求直接落到本地开发服务器(4200端口),而本地没有对应路由,所以返回404。

解决办法

修改proxy.conf.js的context数组,同时覆盖精确路径和子路径场景:

方案一:同时添加精确路径和带通配符的路径

const PROXY_CONFIG = [
    {
      context: [
        "/fi/ameribor",
        "/fi/ameribor/*"
      ],
      target: "http://localhost:10000",
      secure: false,
      changeOrigin: true
    }
  ]
  
module.exports = PROXY_CONFIG;

方案二:使用**通配符匹配所有后代路径(含当前路径)

const PROXY_CONFIG = [
    {
      context: [
        "/fi/ameribor/**"
      ],
      target: "http://localhost:10000",
      secure: false,
      changeOrigin: true
    }
  ]
  
module.exports = PROXY_CONFIG;

修改后重启本地开发服务器,代理即可正常转发/fi/ameribor和其下所有子路径的请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:34:54