The CORS policy has blocked access to XMLHttpRequest at 'https://saja.smjd.ir/api/Account/login' from the specified origin 'http://**'

I have successfully completed my project using Angular 9 on the frontend and asp.net core 3 on the backend, and deployed it to a server. However, I am facing an issue when trying to obtain or use a token from the server.

Access to XMLHttpRequest at 'https://**/api/Account/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
**/api/Account/login:1 

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "https://**/api/Account/login", ok: false, …}
Failed to load resource: net::ERR_FAILED

The backend works fine locally but encounters issues on the host which is of Linux type. Is this a problem with the host configuration or an Angular-related issue? Your assistance is much appreciated.

Login.ts:

constructor(private Service: RegisteredUsersService) { }

  ngOnInit(): void { }
  formLogin = new FormGroup({
    userName: new FormControl('', Validators.required),
    password: new FormControl('', Validators.required)
  });
  onSubmit() {
    this.Service.postDataLogin(this.formLogin.value).subscribe(
      res => {
       consile.log(res);
      },
      err => {
       console.log(err);
      }
    )
  }

RegisteredUsersService.ts:

constructor(private http: HttpClient) { }
  private urlAccount: string = "https://**/api/Account";
  postDataLogin(user): Observable<IResLogin> {
    const url = this.urlAccount + '/login';
    return this.http.post<IResLogin>(url, user);
  }
}

Backend:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<EvaluationDbContext>();
                context.Database.EnsureCreated();
            }

            app.UseCors("ExamCors");
            app.UseAuthentication();

            app.UseHangfireServer();
            app.UseHangfireDashboard();

            app.UseStaticFiles();

            app.UseMvcWithDefaultRoute();



            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("The Evaluation Project Is Running...");
            });
        }

In Configuration:

services.AddCors(options =>
            {
                options.AddPolicy("ExamCors", builder =>
                {
                    builder
                        .AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
            });

Answer №1

It appears that there is a configuration issue on the server end. Due to security concerns, the use of AllowCredentials and AllowAnyOrigin together is not permissible.

To rectify this, replace AllowAnyOrigin() with specifying the specific origins required.

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

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...

Tips for displaying a populated ViewBag string from a try/catch block on the screen

I'm currently working on parsing a JSON file in my controller and implementing try/catch functionality for any errors that may arise. When an error occurs during the JSON parsing process, I populate ViewBag with the error message and attempt to displa ...

Navigating with Angular: The URL for the home page should be set as http://localhost:4200/

I recently implemented URL routing in my project, but I have encountered an issue. Upon redirecting to the home page, the URL changes to http://localhost:4200/home. However, I would like the URL for the home page to simply be http://localhost:4200/ instea ...

Adding or subtracting values in Angular framework to manipulate numbers

I am looking to increment a number from 1 to 50. I attempted to use the following code, but unfortunately the function is not working properly. See Demo Here Here is the HTML: <Button text="+" (tap)="plus()"></Button> <Button text="-" (t ...

What is the proper method for transferring a JWT token to an external URL?

I currently have two REST endpoints set up: accounts.mydomain.com/login - This is an identity provider that sends a JWT token as a response once a user is authenticated with their username and password. api.mydomain.com/users - This endpoint accepts the ...

Using Vivus.js in an Angular 5 Component

I am currently facing some challenges while attempting to incorporate Vivus.js library into Angular 5. The issue seems to be arising from the constructor of Vivus, which suggests that the library is being loaded correctly but not recognizing my element id. ...

How can Angular CLI add extra static resources while live reloading?

Currently, I am utilizing the most recent version of the Angular CLI. The issue I'm facing involves mock http calls that reference local JSON files such as '../app/myfile.json'. When I reload the application, I consistently encounter 404 err ...

The unit test is running successfully on the local environment, but it is failing on Jenkins with the error code TS2339, stating that the property 'toBeTruthy' is not recognized on the type 'Assertion'

I've been tackling a project in Angular and recently encountered an issue. Running 'npm run test' locally shows that my tests are passing without any problems. it('should create', () => { expect(component).toBeTruthy();}); How ...

Code for Stripe Connect processed through AWS Amplify's authentication system

Within the structure of my Angular application, I have successfully integrated AWS Amplify with OAuth and Hosted UI, resulting in a seamless connection process. Specifically, when attempting to link with Google, I am directed back to an URL similar to http ...

Reference ngFor for Input Validation Template

I'm currently facing an issue with validating input fields within a *ngFor loop. I am struggling to create unique template references for each input field. Basically, I need all input fields to be required on submit unless at least one of them is fill ...

Stop automatic variable updates in Angular

In Angular, variable x is assigned to variable y. Whenever variable x changes, y also gets changed. How can this behavior be prevented? ngOnInit() { this.editFunction() } editFunction(){ for (let i = 0; i < this.editingData["tags"].length; i ...

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

``There seems to be an issue with Angular2 routing not functioning properly due to the presence of

Seeking assistance with an issue I'm facing. I am attempting to pass parameters in routing. However, when my parameter contains a slash symbol, Angular interprets the text after the slash as another parameter, causing my routing to fail. { path: &ap ...

Triggering a button click to upload a file from within a grid view

I'm having trouble uploading a file when the "Fileupload" control inside gridview changes. I want to save the file content in DB as soon as it is uploaded by the user. I tried manually triggering the click event of the button control on the change of ...

Developing personalized modules in Angular version 6

I am diving into the world of Angular customization and I have a goal of developing a flexible module in Angular 6. My plan is to create this module and place it in the Node_modules folder so that it can be easily utilized by other teams within the organi ...

The sendKeys function in Selenium seems to be missing some characters when inputting text

Currently, I am working on test automation using Java, Selenium, and Chrome. Our developers recently made an upgrade from AngularJS to Angular2 for our UI. Ever since the upgrade, I've been facing an issue where sendKeys is inputting incomplete charac ...

Utilizing session management in Angular while handling CORS origin requests

Everything was going smoothly with my session until I decided to enable CORS. Server: app.use(require('express-session')({ secret: 'some key', resave: true, saveUninitialized: true, proxy: true, cookie: { s ...

Tips for improving DOMContentLoaded performance with Angular2

Currently, I am in the process of converting a JQuery template to Angular 2, specifically a Dashboard-like template. This website has numerous popups, each containing multiple tabs, so I decided to separate each popup into different components to keep the ...

Semantic HTML in Angular

Having a React background, I'm used to custom components rendering as expected without any extra wrapper tags. However, in the case of Angular, I've noticed that my custom component my-custom-component adds an additional tag around the content. & ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...