Multiple values are present in the 'Access-Control-Allow-Origin' header

Encountered the following error when running my website:

Failed to load http://localhost:54721/api/Auth/GetMenuItemsByRoleId/null: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:4200, *', but only one is allowed. Origin 'http://localhost:4200' is therefore not allowed access

To resolve this issue, I have added the following code in every controller, which has been effective.

[EnableCors("http://localhost:54721/", "*", "*")]

This approach fixed the error, however applying it in each controller is not ideal.

Is there a more efficient solution that can be implemented in one place, like the web.config file?

The startup.cs file looks like this:

public partial class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration httpconfig = new HttpConfiguration();

            WebApiConfig.Register(httpconfig);
            //enable CORS for origin requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        
            ConfigureOAuth(app);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            double timeout = Convert.ToDouble(ConfigurationManager.AppSettings["Timeout"].ToString());
            OAuthAuthorizationServerOptions OAuthserverOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(10),
                Provider = new SimpleAuthorizationServerProvider()
            };

            //Token generation
            app.UseOAuthAuthorizationServer(OAuthserverOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }

Answer №1

A solution definitely exists and it is highly recommended that you utilize it.

To implement this, consider creating a configuration class following the guidance provided in this example.

Your current cors setup is not correct. Make sure to allow http://localhost:4200 rather than your API's URL http://localhost:54721.

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

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...

Issue with loading React Router custom props array but custom string works fine

I am facing an issue with my ReactTS-App where I pass a prop via Router-Dom-Props to another component. The problem arises when I try to use meal.food along with meal.name, or just meal.food alone - it doesn't work as expected. Uncaught TypeError: mea ...

Step-by-step guide on generating a deb or exe file for an Angular Electron application

I am currently developing an Angular 6 project and I have a desire to turn it into a desktop application using Electron. After successfully installing Electron in my project, I encountered some challenges when trying to create builds for multiple platforms ...

Retrieving targeted information from the store following the retrieval of data from an API

In my project, I have set up an RXJS effect that loads an organization from the server upon a certain action. Once the organization is loaded, I attempt to select a bookmark from the NGRX store based on the organization ID. Finally, I dispatch a success ac ...

What methods does TypeScript use to verify primitive types during runtime?

Is it true that Typescript removes any type or interface at compile time? If so, how is it possible to determine an object's primitive type using the typeof keyword? Are custom interfaces handled differently than primitive types? const a = "strin ...

unable to retrieve the values of the rowdata in GridOption

ngOnInit(): void { this.fetchAllAnimeReviews(); } public fetchAllAnimeReviews(){ this.animeservice.getAllAnimeReviews() .subscribe( response => { this.Anime = response; this.gridOption = this.createGridO ...

Issue: Module "expose?Zone!zone.js" could not be located

Just started experimenting with Angular 2 and encountering an issue when importing zone.js as a global variable: https://i.stack.imgur.com/gUFGn.png List of my packages along with their versions: "dependencies": { "angular2": "2.0.0-beta.3", "es ...

Effortlessly bring in Typescript namespace from specific namespace/type NPM package within a mono-repository

Instead of repeatedly copying Typescript types from one project to another, I have created a private NPM package with all the shared types under a Typescript namespace. Each project installs this NPM package if it uses the shared types. index.d.ts export ...

Exploring the functionality of maximizing and minimizing logic in an Angular Bootstrap modal popup

I'm currently utilizing Angular Bootstrap Modal Popup and I'd like to include options for Maximize and Minimize in addition to the close button. By clicking on the maximize option, the popup should expand to full screen, and by clicking on minimi ...

Tips for resolving the issue of 'undefined' object in TypeScript with Angular 14

Previously, the below code worked fine in Angular for me. However, I am now encountering an error in Angular 14 stating Object is possibly undefined: this.progress = Math.round(100 * event.loaded / event.total); The issue seems to be with the event.total ...

Generate div elements with a row capacity of 3 and a column size of N

I am trying to arrange divs in a way that they can be scrolled horizontally. I have set up a flex container, but I'm unsure what other steps are needed to ensure the boxes align to the left. You can view the demo code here .container { height: 95px ...

Angular frontend failing to send authorization cookie for cross-origin requests, despite using withCredentials

Today, I've been facing a persistent issue that I just can't seem to figure out. I have my Angular frontend running on localhost:4200 and a Spring Boot backend on localhost:8080. When I call the localhost:8080/api/login endpoint from my Angular ...

How can I apply concatMap in Angular?

Can you please guide me on how to effectively utilize concatMap with getPrices() and getDetails()? export class HistoricalPricesComponent implements OnInit, OnDestroy { private unsubscribe$ = new Subject < void > (); infoTitle ...

Determine the subtotal for a particular item using AngularJS

Is there a way to apply the sub total amount to a specific item only? Currently, in my stackblitz example, when I add a new item and change the quantity of that last item, all recently added items also get updated. I want to modify the "changeSubtotal()" ...

Angular 6 Exporting Data to CSV File

Recently, I've started working with Angular and I'm currently involved in a project that requires CSV export functionality. The project uses Angular 6 on the frontend and Laravel on the backend. Below is the Laravel function I wrote using mattwe ...

Is there a way to attach an event listener to a span that was inserted using DTColumnBuilder?

I am attempting to include an onclick event for a span element that is generated by DTColumnBuilder. DTColumnBuilder .newColumn('Invoice') .withTitle('<span class="li-table-head ...

Spying on ActivatedRoute.queryParams is not possible in Angular when using Jasmine

Is there a way to effectively spy on a stubbed Angular Service method that should return an Observable like ActivatedRoute.queryParams? The below code snippet shows my failing test case: import { TestBed, ComponentFixture } from "@angular/core/testing"; i ...

How can Mui typescript be extended with a unique wrapper that includes a `component` property?

I recently created a unique wrapper component: import Box, { BoxProps } from "@mui/material/Box"; type CustomWrapperProps = { id: string } & BoxProps const CustomWrapper = (props: CustomWrapperProps) => { const {id, children, ...rest ...

Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors? In this example (run), this.x is accessed in the method initY before it's initialized in the constructor: class A { readonly x: number rea ...

`Cannot retrieve object`

this.deleteValue = { LanguageId : '', LanguageName : '', LongName : '', CreatedBy : '', UpdatedBy : '', CreatedDate : '', ...