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

POST请求自动拼接localhost:4200前缀 如何移除该异常前缀

问题原因

你配置的environment.apiBaseUrl缺少http://或https://协议前缀,浏览器会将无协议的地址识别为相对路径,自动拼接当前前端项目运行的根地址(即本地开发环境的http://localhost:4200/),最终生成错误的请求地址。

修复方法

  • 修改环境变量中的apiBaseUrl配置,补全协议头即可,将原有值192.168.0.26:8080调整为http://192.168.0.26:8080。
  • 可新增容错逻辑避免后续配置遗漏协议头时复发同类问题,参考代码如下:
// 封装接口地址拼接工具方法
function getApiUrl(suffixPath: string) {
  let fullBasePath = environment.apiBaseUrl + environment.path;
  // 自动补全http协议头
  if (!fullBasePath.startsWith('http://') && !fullBasePath.startsWith('https://')) {
    fullBasePath = 'http://' + fullBasePath;
  }
  return fullBasePath + suffixPath;
}

// 改造后的login方法
login(value) {
    console.log("enviroment => ", environment.apiBaseUrl + environment.path);
    return this.http.post(getApiUrl('/auth/login'), value)
      .pipe(
        tap(res => this.setSession),
        shareReplay()
      );
  }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:51:02