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

Encountering a problem when utilizing window.ethereum in Next Js paired with ether JS

Experiencing some difficulties while utilizing the window.ethereum in the latest version of NextJs. Everything was functioning smoothly with NextJs 12, but after upgrading to NextJs 13, this error started popping up. Are there any alternative solutions ava ...

Strategies for iterating over an array in React with TypeScript

I'm currently working on looping through an array to display its values. Here's the code I have: ineligiblePointsTableRows() { return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => { return { applied: (&l ...

Attributes for data validation in ASP MVC model are important for ensuring the

Utilizing data annotation attributes for client side validation metainfo is crucial to ensure accurate input handling. In the given code snippet, data-val-date attribute is successfully added to the html input element: [DataType(DataType.Date)] pu ...

What is the best way to retain all checkbox selections from a form upon submission?

I have a batch of checkboxes that correspond to the profiles I intend to store in the database. HTML: <tr *ngFor="let profile of profiles | async"> <input type='checkbox' name="profiles" value='{{profile.id}}' ng-model=&apo ...

How can we verify that console.log has been called with a specific subset of expected values using Jest?

I am currently experimenting with a function that adds logging and timing functionality to any function passed to it. However, I am facing a challenge when trying to test the timing aspect of it. Here are my functions: //utils.js export const util_sum = ( ...

Navigate through an unidentified variable in a different scope from its origin

Currently, I am working on writing a unit test for an MVC web application. The purpose of this test is to validate whether the returned list of anonymous variables in a jsonresult is accurate. However, I am facing difficulty in iterating through this list. ...

Modifications made to Angular 7 templates are not appearing in MVC 5

Currently, I am utilizing Angular 7 with MVC5 in Visual Studio 2019. However, I have encountered an issue while trying to render the Angular template in my index.cshtml file. I access the Angular template in index.cshtml using ``. The template loads perfec ...

Retrieve information and transform it into a dynamic variable using Firebase

I am trying to retrieve data from the current user, specifically their company named "ZeroMax", and then store this data in a global variable. The purpose of this variable is to define the path for Firebase. I believe my code gives a clear understanding of ...

Is it possible to create an instance in TypeScript without using class decorators?

As per the definition on Wikipedia, the decorator pattern enables you to enhance an object of a class with additional functionalities, such as: let ball = new BouncyBall(new Ball()) The Ball object is adorned with extra features from the BouncyBall class ...

Strategies for handling superfluous or calculated information within Angular form components

I am faced with a challenge in managing informative fields within my component, especially when some inputs are derived from others. For instance, consider an order that includes a product ID and an amount. Here is a scenario: If a product is selected, I ...

Reset the select boxes when a button is clicked

I'm currently utilizing Devextreme within my Angular application, and I have three dx-selectbox elements in the component. I am attempting to clear all three dropdown selections when clicking a "clear" button. Unfortunately, I am unable to find a way ...

Ways to retrieve the initial 4 elements from an array or class organized by their price entries in ascending order

Let's say we have an array of objects representing products: Products: Product[] = [ { id: 1, name: 'Milk', price: '1' }, { id: 2, name: 'Flour', price: '20' }, { id: 3, name: 'Jeans', pri ...

Utilize personalized Bootstrap variables within your Angular application

I am attempting to customize the default colors of Bootstrap within my Angular project. I have established a _variables.scss file in the src directory. Within this file, I have included the following code: $primary: purple; Next, I imported my _variables ...

The parameters 'event' and 'event' are not compatible with each other

I'm currently working on a page that involves submitting a form: import React from 'react'; import Form from 'react-bootstrap/Form'; import { useSignIn } from '../../hooks/Auth/useSignIn'; import { useHistory } from &apos ...

Where should the chromedriver.exe file be placed when preparing to release the Selenium WebDriver C# project?

I currently have my chromedriver.exe saved in my local documents and it is functioning properly. However, I need to deploy it to production now. I am looking for a way to bundle it with my software and reference it locally. What is the best approach to lo ...

React: Issue with passing arguments to redux action hooks

In my React application, I have implemented Redux-Toolkit to manage reducers and actions with slices. I am currently working on creating actions that can update and delete values from the store, requiring arguments for their usage. To achieve this, I have ...

Issue "A system error of type 'System.IO.IOException' that was not properly addressed was encountered in mscorlib.dll"

I encountered a specific error message and need help resolving it: An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll Additional information: The process cannot access the file because it is being used by another pro ...

Exploring the possibilities of combining Angular-CLI and the latest Bootstrap

Embarking on my journey with Angular 2, I decided to use the official angular-cli tool to create a new project. Creating a new project was straightforward: ng new [my-project-name] The project was successfully created and ready for customization. Wanti ...

Easily retrieve the value of a form control when it is changed with Form

Currently, I am in the process of reviewing Formly. In my initial attempt, I am trying to trigger a method when the content of a textarea changes. The code snippet below shows what I have tried so far. Unfortunately, it seems like the functionality is no ...

The reason behind the clickable issue with my duplicate <ion-select>

I've been working on a form using HTML, CSS, and JavaScript where I implemented an "Add" button to duplicate the form. The issue arises with the ion-select element within the duplicated form. While the original form displays all predefined options upo ...