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
相关产品推荐
相关产品推荐

