为什么angular向https://localhost:4200而不是http://localhost:5001发出http请求,以从Restful www.example.com获取数据Asp.net?

ftf50wuq  于 2022-12-05  发布在  .NET
关注(0)|答案(1)|浏览(188)

我使用的是angular版本15.0,后台一切正常,但在前台,当服务请求获取数据时,不幸的是,出现了一个错误,如下所示:

Failed to load resource: the server responded with a status of 404 (Not Found)

因为请求URL为:

http://localhost:4200/api/commodityTypes/getAllCommodityTypes

另一方面,当我们使用Swagger与这个URL:
已成功提取所有商品类型数据。
服务代码是:

@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

如何解决此问题?

z31licg0

z31licg01#

我认为您应该调整您的baseUrl:

export class CommodityTypesService {

  private baseUrl = https://localhost:5001/api/CommodityTypes;

如果出现CORS错误:

对于来自localhost:5001的请求,您必须在后端中启用CORS

相关问题