What could be the reason behind Angular choosing to send an HTTP request to `https://localhost:4200` instead of `http://localhost:5001` in order to retrieve data

Using Angular version 15.0 has been smooth sailing on the backend, but when making service requests on the frontend, an error is encountered:

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

This is due to the request URL:

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

On the other hand, accessing the same URL through Swagger works fine:

https://localhost:5001/api/CommodityTypes/getAllCommodityTypes retrieves data successfully.

The service code snippet for this issue is as follows:

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

The encountered error message 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 this issue be resolved?

Answer №1

I suggest updating the baseUrl in your code:

export class CommodityTypesService {

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

Solving the CORS Issue:

To resolve the CORS error, you need to enable CORS on your server for requests originating from localhost:4200. In your backend's Startup.cs, consider implementing the solution provided in this thread (it worked for me):

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

Make sure to place

app.UseCors("AllowOrigin");
at the top of other middlewares.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to developing a class extension in ASP.NET Core

I am looking to create a custom service using the userManager, but I am unsure how to access the dbContext. public static class UserManagerExtensions { public static async Task<IdentityResult> AddProfileAsync(this UserManager<ApplicationUser& ...

Utilizing Electron: Integrating Native Binary Dependencies Through Webpack

I am exploring the use of Webpack in my electron project to bundle the Typescript code in the main process (the renderer is managed as an Angular project with the CLI). However, in my main process, I rely on registry-js: import { enumerateValues, HKEY } ...

Troubleshooting ngFor in Angular 5

I'm currently working on a component that needs to display data fetched from the server. export class CommerceComponent implements OnInit { dealList; ngOnInit() { this.getDeals(); } getDeals(){ this.gatewayService.se ...

In Typescript, invoking toString() does not alter the data type of the property

When I encounter the error in the valorControlo property, it states: The 'valorControlo' property does not exist on the type 'string'. Even after adding the toString(), the issue persists. Here is the snippet of code: const [isBarExten ...

Issue with asynchronous function: "Cannot assign type 'Promise<MyType[]>[]' to type 'MyType[]'"

After converting this function to async, I've been encountering issues with type annotations being out of sync: export default async function formatCallRecordsForPGPromise( rawCalldata: CallRecord[], ): Promise<SaveableCallRecord[]> { const ...

Acquire the `ICredentials` interface using Windows Authentication

Currently, my system is utilizing Windows Authentication for login. In order to access a particular service, it is necessary to authenticate using an ICredentials object. However, I would like to find a way to obtain these credentials without prompting th ...

To emphasize the chosen item following a component's update

SCENARIO: A component named list is used to display a list of all customers. The conditions are as follows: 1) By default, the first list-item (e.g. customer 1) is selected and emitted to another component called display. 2) When any other list-item (i.e ...

What is the process for importing an untyped Leaflet plugin into an Angular application?

I am trying to incorporate the leaflet plugin leaflet-mapwithlabels into my angular project. However, the library does not provide an option for NPM installation. After following some guides, I attempted adding the JS file directly to the node-modules in i ...

Revamping an npm package on GitHub

Currently, I am managing a project that has gained popularity among users and has received contributions from multiple individuals. The next step I want to take is to convert the entire library into TypeScript, but I am unsure of the best approach to ach ...

Trouble Ensues When Implementing Angular 9 Template Driven Form Validation and Setting Focus to the Next Field Simultaneously

Angular 9 is used for my template-driven login form. <form name="login" #loginForm="ngForm" (ngSubmit)="loginForm.form.valid && login()" *ngIf="loginPage" novalidate> <ion-item> &l ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

Is it feasible to use Angular2 in conjunction with ui-calendar?

Entering the fascinating world of Angular 2 has me feeling like a beginner again. My team and I had been utilizing angularjs with ui-calendar in our project, but now we're transitioning to Angular 2 due to new production requirements. The challenge ar ...

What are some methods to prevent cookies from being overridden?

Just beginning my journey in web development. Currently utilizing asp.net Web API and Angular with token authentication. Every time a user logs in, I set the token in a cookie and send it with each request. Everything has been running smoothly so far, bu ...

FIREBASE_AUTHCHECK_DEBUG: Error - 'self' is undefined in the debug reference

I'm encountering an issue while trying to implement Firebase Appcheck in my Next.js Typescript project. firebase.ts const fbapp = initializeApp(firebaseConfig); if (process.env.NODE_ENV === "development") { // @ts-ignore self.FIREBASE_ ...

"Enhance your forms with RadixUI's beautiful designs for

New to Radix UI and styling components, I encountered difficulties while trying to adapt a JSX component to Radix UI: Utilizing Radix UI Radio Groups, I aim to style my component similar to this example from Hyper UI with grid layout showing stacked conte ...

Is there a way to tally the checked mat-radio-buttons in Angular?

I am seeking a way to determine the number of radio buttons checked in a form so I can save that number and transfer it to a progress bar. <mat-radio-group name="clientID" [(ngModel)]="model.clientID"> <mat-radio-button *ngFor="let n of CONST ...

Typescript error encountered in customized PipeLine class

I am currently developing a web scraping application using Puppeteer. In this project, I aim to create a PipeLine class that will take the current instance of the page and expose an add method. This add method should accept an array of functions with the t ...

Issue: The error message "TypeError: React.createContext is not a function" occurs when using Next.js 13 alongside Formik with TypeScript

I'm currently working on creating a form using Formik in NextJs 13 (Typescript). However, the form I designed isn't functioning properly. To troubleshoot, I added code snippets from Formik's examples as shown below. Unfortunately, both my fo ...

Issue in Typescript: The type 'RegExpMatchArray' cannot be assigned to a parameter of type 'string'

Here is the code snippet I am working with: import { persistState } from 'redux-devtools'; const enhancer = compose( applyMiddleware(thunk, router, logger), DevTools.instrument(), persistState( window.location.href.match(/[?&]debu ...

Tips for adding multiple string values to a single node in the built-in LinkedList type in MVC ASP.NET

As a newcomer in this field, I am facing a challenge with retrieving data from a table called comment. My goal is to retrieve multiple columns and rows of data, where each row has two columns. I am wondering if it is possible to use a Linked List to pass ...