There is an issue with the Angular front-end receiving errors while trying to access the API on the C

In my current setup, I have an Angular front-end communicating with a C# webAPI back-end. The Angular application is able to fetch data from external URLs like and json-server --watch db.json. On the other hand, the C# webAPI successfully responds to API calls made through browsers or Postman (using Get method at http://localhost:49566/api/people). However, when the front-end tries to interact with the back-end, it encounters the following error message:

HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
(XHR)OPTIONS - http://localhost:49566/people

I am seeking advice on identifying where the issue lies, whether it is in the front-end implementation or the back-end setup.

Despite referring to various Angular HttpClient examples, I am still facing the same problem - communication works fine with external URLs but fails with my C# webAPI URL.

I attempted to include a post option as well, but that did not offer a solution.

The C# code snippet:

 [HttpGet]
    public IEnumerable<Person> Get()
    {
        return SQLiteDataAccess.GetPeople();
    }

Here's the code for the Angular data service:

export class DataService {
  people: object;

  constructor(private http: HttpClient) { }

  searchClick(searchString: string) {
    return console.log('clicked ' + searchString);
  }

  getPeople() {
    const httpOptions = {
      headers: new HttpHeaders({
          'Access-Control-Allow-Origin': 'http://localhost:4200/',
          'Access-Control-Allow-Methods': 'GET',
          'Access-Control-Allow-Headers': '*',
          'Content-Type': 'application/json',
          'Accept': 'application/json'
      })
    };
    return this.http.get('http://localhost:49566/api/People', httpOptions )  
}
}

My objective is to enable the front-end to efficiently fetch data from the back-end so that I can display it on the application.

Answer №1

Modify

   adjust this.http.get('http://localhost:49566/api/People', httpOptions )

to

   update this.http.get('http://localhost:49566/api/people', httpOptions )

The address is sensitive to casing.

Best of luck!

Answer №2

The problem lies in the CORS issue on the server-side and the method signature configuration.

To resolve this, begin by enabling CORS in your API code (written in C#). You can refer to MSDN for the appropriate namespaces/dlls required (e.g. System.Web.Cors).

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Configure web API services
            config.EnableCors();

In your API controller's derived class, ensure that CORS is allowed. Use * to allow all URLs access. Make changes according to your client's (Angular app uri) requirements.

/// <summary>
    /// Provides API for Order entity.
    /// </summary>
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class OrderController : ApiController
    {

A pre-flight request with the method OPTIONS is sent in CORS to determine if it is safe to send the request with specified parameters. This occurs before a GET or POST request is made.

Ensure that the following configuration is present in your web.config:

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

<remove name="OPTIONSVerbHandler" />
prevents IIS from intercepting OPTIONS requests.

Additionally, in the web.config, make sure that GET, POST, and OPTIONS methods are allowed:

<httpProtocol>
      <customHeaders>            
        <!--...omitted for brevity-->

        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
      </customHeaders>

Lastly, implement the following method:

[HttpGet]
public IEnumerable<Person> Get()
        {
            return SQLiteDataAccess.GetPeople();
        }

No modifications are necessary in the Angular client-side code regarding CORS. Hopefully, this information is helpful.

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

What is the best way to get the *ngfor to function properly within a modal window?

I am encountering an issue with the *ngfor directive as the modal is not functioning correctly. <table *ngFor="let wt of wtl"> <tr> <td *> <mat-form-field style=&quo ...

What sets apart `tsc --build --clean` from `rm -rf *.js` command?

I'm curious about the tsc command with the arguments --build --clean, which is used to clean/remove the generated .js files from the Transpiler (tsc). What makes this command special or significant? If I simply need to delete all the .js files, I can ...

Encountering a 'blocked:other' error status while making a REST API call in my Angular application to retrieve data from the server

Example of the requested REST API URL: http://example.com/controller/api?bannerId=1&value=23 Encountering a browser error status: blocked:other while attempting to make an HTTP request to the server from the Angular application. ...

Guide to utilizing @types/node in a Node.js application

Currently, I am using VSCode on Ubuntu 16.04 for my project. The node project was set up with the following commands: npm init tsc --init Within this project, a new file named index.ts has been created. The intention is to utilize fs and readline to read ...

Customize Angular loaders for individual files

Our current codebase was originally built with Angular, utilizing the Angular CLI and its default webpack configuration. However, as we transition towards using web components, we are faced with the challenge of incorporating SCSS within our web component ...

Make sure to verify the Json data when invoking DeserializeObject<Object>( ... ) function

Is there a way to validate Json code as I deserialize it? For instance, if I receive the following ... using Newtonsoft.Json; ... public Car { public int Year{ get; set; } public String Make{ get; set; } } ... JsonConvert.DeserializeObject<Car> ...

I am unable to display the service response in the Angular component

I'm facing an issue with displaying data in an angular component from a service. The process from the service to the component seems fine, but when I try to use the variable in HTML, it doesn't show the result. For this project, I am using the M ...

experimenting with the checked attribute on a radio button with jasmine testing

Currently using Angular 8 with Jasmine testing. I have a simple loop of radio buttons and want to test a function that sets the checked attribute on the (x)th radio button within the loop based on this.startingCarType. I am encountering false and null tes ...

Strange issue: Inconsistent 60-40 database update ratio when generating records in ASP.NET MVC 3 with Razor and SQL Server 2008 R2

Hey everyone, I'm experiencing a strange issue in my MVC3 project. I'm using C# for programming, SQL Server 2008 R2 as the server, and Linq-to-SQL. When I try to create new records, sometimes they update successfully, but other times they don&ap ...

Lazy-loaded modules in Angular that contain services provided within the module

Currently, I am facing a challenge with lazy-loaded modules and services that are provided in these modules. My folder structure looks like this: app -> featureModule1 (lazy loaded) -> featureModule2 (lazy loaded) -->services --->servi ...

How can I import a CSS file when creating a UserControl via a Webpart?

Everything is ok. i van see StyleSheet.css in page source.But css effect can not run my gridview. How can i do that public class MyGridView : WebPart { GridView gvCustomers; protected override void CreateChildControls() { ...

Module not found: Lazy loading issue in Angular 5

Despite my efforts to implement lazy loading, I am encountering an error stating "Cannot find module" and cannot figure out why. Here is the setup of my environment: - Angular 5.2.1 - .NET Core 2 - Webpack 3.10.0 - angular-router-loader 0.8.2 - @ ...

Error: No parameter constructor identified

Good day! I'm currently setting up the interface in the Global.ascx file as shown below: private static SimpleMembershipInitializer _initializer; private static object _initializerLock = new object(); private static bool _isInitialized; public Sim ...

Transform intricate attribute of an object into a singular value

Consider a scenario where we have the two classes defined as follows: public class A { public string Name { get; } = "Johny Bravo"; public B ComplexProperty { get; } = new B(); } public class B { public string Prop1 { get; } = "value1"; p ...

How can I restrict the highest possible date selection in reactjs?

I am working on a project that requires users to select dates using datetime-local, but I want to limit the selection to only three months ahead of the current date. Unfortunately, my current implementation is not working as expected. Any assistance woul ...

Combine two lists in LINQ without any common columns

I am faced with the challenge of merging two distinct lists retrieved from a database: List<Id> lstId containing values 0,1,2,… List<name> lstnaname holding values “a”,”b”,c” The task at hand is to combine these lists without any ...

Displaying nested web service array data in Angular 4

I created a project that retrieves data from a web service API. However, the API contains nested arrays that also need to be displayed. How can I access the data from these nested JSON arrays? What is the correct way to extract this data within the HTML co ...

Applying these sorting functions to my specific scenario

Hello everyone, I hope you can help me out with this issue. I have been struggling for hours trying to sort my array of objects in JavaScript based on a specific property, but I just can't seem to get it right. I have referred to some of the top post ...

The error message "Directive does not contain a property called 'element'.ts" is displayed

I'm encountering an issue where the property 'element' is not recognized on 'directive'. I am currently working on implementing functionalities for directives. import { Directive, ElementRef, HostListener } from '@angular/cor ...

Apologies, but your payment request was not successful. Please try using an alternative payment method or reach out to us for assistance. Find out more information about error code [OR

While trying to test Google Pay using a fake card, I encountered an error message stating: Your request failed. Use a different payment method, or contact us. Learn more [OR-CCSEH-21]. Below is the Angular code snippet that I am working with: paymentReques ...