Angular 15请求指向localhost:4200而非5001导致404的解决方法
Angular 15 调用ASP.NET后端接口404问题排查与解决
问题概况
- 后端ASP.NET Restful接口运行正常,通过Swagger访问
https://localhost:5001/api/CommodityTypes/getAllCommodityTypes可成功获取数据 - 前端Angular 15服务发起请求时返回404,请求URL为
http://localhost:4200/api/commodityTypes/getAllCommodityTypes - 前端服务代码:
@Injectable({ providedIn: 'root' }) export class CommodityTypesService { private baseUrl = 'api/commodityTypes'; constructor(private http: HttpClient) { } /** GET all commodityTypes from the server */ getAllCommodityTypes(): Observable<CommodityType[]> { return this.http.get<CommodityType[]>(this.baseUrl + '/getAllCommodityTypes/'); } // rest of code ... }
- 错误信息:
HttpErrorResponse error: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /api/commodityTypes/getAllCommodityTypes/</pre>\n</body>\n</html>\n" headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure response for http://localhost:4200/api/commodityTypes/getAllCommodityTypes/: 404 Not Found" name: "HttpErrorResponse" ok: false status: 404 statusText: "Not Found" url: "http://localhost:4200/api/commodityTypes/getAllCommodityTypes/" [[Prototype]]: HttpResponseBase
核心问题
- 请求目标错误:前端请求直接指向Angular自身的
4200端口,而非后端的5001端口 - 路径大小写不匹配:后端接口路径是
api/CommodityTypes/getAllCommodityTypes(CommodityTypes首字母大写),前端请求的是小写的api/commodityTypes/...,部分服务器环境对路径大小写敏感 - 结尾斜杠冗余:前端请求URL末尾多了一个斜杠
/getAllCommodityTypes/,后端接口可能未处理带结尾斜杠的请求
解决方法
方法一:配置Angular代理转发(推荐)
在Angular项目根目录创建proxy.conf.json文件,内容如下:
{ "/api/*": { "target": "https://localhost:5001", "secure": false, "changeOrigin": true } }
修改angular.json中的serve配置,添加代理文件引用:
"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "你的项目名称:build", "proxyConfig": "proxy.conf.json" } }
重启Angular开发服务,此时前端请求/api/...会自动转发到后端https://localhost:5001/api/...
方法二:直接指定完整后端地址
修改CommodityTypesService中的baseUrl,直接指向后端服务,并修正路径大小写与结尾斜杠:
private baseUrl = 'https://localhost:5001/api/CommodityTypes'; getAllCommodityTypes(): Observable<CommodityType[]> { return this.http.get<CommodityType[]>(this.baseUrl + '/getAllCommodityTypes'); }
方法三:统一路径规范
如果后端允许,调整后端接口路由为小写;或者确保前端请求路径与后端完全一致,同时去掉URL末尾的斜杠:
private baseUrl = 'api/CommodityTypes'; getAllCommodityTypes(): Observable<CommodityType[]> { return this.http.get<CommodityType[]>(this.baseUrl + '/getAllCommodityTypes'); }
内容的提问来源于stack exchange,提问作者R. Nourmandi
相关产品推荐
相关产品推荐

