Allowing cross-origin resource sharing (CORS) in .NET Core Web API and Angular 6

Currently, I am facing an issue with my HTTP POST request from Angular 6. The request is successfully hitting the .net core Web API endpoint, but unfortunately, I am not receiving the expected response back in Angular 6. To make matters worse, when checking the console, I encountered the following error:

"Access to XMLHttpRequest at 'http://localhost:55654/api/login/auth' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Curiously, I find it perplexing that even though there might be a CORS access enabling issue, the API call is still being reached. Despite this, I am unable to receive the desired response.

The code snippet for the Angular 6 HTTP POST request is as follows:

this.http.post("http://localhost:55654/api/login/auth", credentials, {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
}).subscribe(response => {
let token = (<any>response);
localStorage.setItem("jwt", token);
}, err => {

});

I have already implemented CORS configurations within my .NetCore Web API using the methods below:

Configure Method in Startup.cs:

...
app.UseCors(options =>
options.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader());
...

ConfigureServices Method in Startup.cs:

...
services.AddCors();
...

Answer №1

To configure CORS in Startup.cs, you can add the following code to ConfigureServices:

services.AddCors();

In the Configure method, include the following code:

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

Implementing these changes should resolve any issues related to CORS.

Answer №2

Just a quick reminder from the comments:

Remember to make sure that app.UseMvc is placed AFTER app.UseCors

...
app.UseCors(options =>
  options.WithOrigins("http://localhost:4200")
    .AllowAnyMethod()
    .AllowAnyHeader());

app.UseMvc();
...

Answer №3

If you're looking to enhance your website's security, consider implementing a Proxy server to access your Backend. Simply create a proxy file (proxy.conf.json) in your root directory.

To run your application with the Proxy configuration, use: ng s --proxy-config [PathToProxy]

Here is an example configuration:

{
  "/api/*": {
    "target": "http://localhost:55654",
    "secure": false,
    "logLevel": "debug"
  }
}

For more information on setting up a Proxy with Angular CLI, check out this link: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

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

Error when building Angular 9 due to missing peer dependencies

In my coding project, there is a specific npm module that has a dependency on electron. The functionality from this module is accessed within a function and only executed when necessary, allowing it to be utilized in both electron-based projects as well as ...

Is there a way to halt the current traversal of visitEachChild in TypeScript Transformer API?

While navigating through each child node of a parent node using visitEachChild, is there a way to stop the process when I no longer wish to visit the subsequent child nodes? For example: Parent node Node 1 Node 2 <-- My target point. Node 3 Node 4 Nod ...

Escaping double quotes in dynamic string content in Javascript can prevent unexpected identifier errors

Need help with binding the login user's name from a portal to a JavaScript variable. The user's name sometimes contains either single or double quotes. I am facing an issue where my JavaScript code is unable to read strings with double quotes. ...

Utilizing Business Logic in a MEAN Stack Environment

When developing an Angular application, where should the calculations take place - on the front end or back end? Considering that the outputs need to update with each input change, is it practical to send a request to the back end every time there is an ...

Angular library modules for node packages

After developing my latest library, I noticed some red underlines: https://i.stack.imgur.com/ffAjI.png In this package, I plan to incorporate other npm packages like ionic and crypto. I attempted to update the package.json within the library: { "name ...

The type of 'username' cannot be determined without specifying the reference to '@angular/forms/forms' in the node modules

I'm encountering an issue with my application: forgot-password.component.ts(44,7): error TS2742: The inferred type of 'username' cannot be named without a reference to '.../node_modules/@angular/forms/forms'. This is likely not po ...

Revamp Your Service Naming and Nickname with Swagger Codegen IO

Is it possible to customize the Swagger IO CodeGen naming conventions for generating Angular API Service Proxies? Check out Swagger Editor here The current convention combines API, Controller Name, Controller Method, and HTTP Action. public apiProductGet ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Form validation on the client side: A way to halt form submission

I have a form with several textboxes. The unobtrusive jquery validation is functioning properly and correctly turns the boxes red when invalid values are entered. However, I've noticed that when I click to submit the form, it gets posted back to the s ...

Can you explain the significance of <this> within TypeScript generics?

Our application employs express along with TypeScript. While exploring their type definitions, I stumbled upon the following snippet and I'm curious about its meaning: export interface IRouter extends RequestHandler { all: IRouterMatcher<this& ...

Angular: Understanding the intricacies of HTTP calls in ngOnInit versus click events (potentially related to caching mechanisms)

Within my Angular application, I have a basic service configured to communicate with the server. The service has been injected into a component. Interestingly, when I directly call one of its methods inside the ngOnInit() method of the component, everythin ...

Encountering a glitch while integrating the angular-select2 module into an Ionic 3 application

Attempting to integrate the angular-select2 npm module into my ionic 3 app. Successfully installed the module using npm within my project Imported the package into my app.module.ts file Added <select2> tags into the html file of my application Enc ...

TypeScript in Angular causing lodash tree shaking failure

I am currently working on a large project that involves TypeScript. Various attempts have been made to optimize the use of lodash in my project. Before making any conclusions, I believe it is important to review the outcomes of my efforts. The command I ...

Error encountered in Vue code, lacks default export on Editor Terminal

I'm not experiencing any issues in the browser, I am getting the desired output. However, why does this keep showing up in the editor terminal? Any assistance would be greatly appreciated. Error - No Default Export: The module "/vue3/src/components/ ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

[Simple TypeScript]: Assign the parameter value as the key of the object returned by the function

How do I modify the key of a function returned object to match its parameter's value? Here is my current code: const createCache = <A, T extends string>(name: T, base = {}) => { const cache = base; return { [name]: cache, } as { ...

How can I implement a master-detail view in Angular 2?

Update: I finally figured it out. After moving all the html from index.html to app.component.ts, everything started working perfectly. The method described below is the correct one. I've been facing an issue where I have a ParentComponent that retrie ...

Merging Type-GraphQL and Typegoose through a Variety of Decorators

Using a combination of Type-GraphQl and Typegoose, I aim to streamline my data definitions by consolidating them into one source for both GraphQL schemas and Mongoose queries. Is it feasible to merge the two libraries in a way that allows me to describe bo ...

Looking to build a unique form validator for two inputs? Ensure that one input number is consistently larger than the other with this guide

Is it possible to create a custom form validator with 2 inputs? My goal is to ensure that one input number is always greater than the other. ValidateMaxMin(control: FormControl) { console.log(control.value.productMin); if (control.value.productM ...