Home > Net >  why angular makes http request to https://localhost:4200 instead of http://localhost:5001 to get dat
why angular makes http request to https://localhost:4200 instead of http://localhost:5001 to get dat

Time:12-05

I am using angular version 15.0, and everything is gone well in backend. but in frontend side, when the service requests to get data, unfortunately, an error is rised a bellow:

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

because the request URL is:

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

other side, when we use Swagger with this URL:

https://localhost:5001/api/CommodityTypes/getAllCommodityTypes data is fetched successfully.

the service code is:

@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 ...
  }

and the error is:

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

how can fix this problem?

CodePudding user response:

I think you should adjust your baseUrl:

export class CommodityTypesService {

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

How to eliminate your CORS Error:

You have to enable CORS in your backend for requests coming from localhost:4200. In the Startup.cs of your backend, you could try to include the code of the accepted answer of the following thread (for me it worked):

Angular 9 and .NET Core - access from origin localhost:4200 has been blocked by CORS policy

Please also note that app.UseCors("AllowOrigin"); must be located on the top of the others middlewares.

  • Related