The preflight request in Angular2 is being rejected due to failing the access control check: The requested resource does not have the 'Access-Control-Allow-Origin' header

I encountered an issue while attempting to execute a basic POST request to establish an account using an API in .NET. The process fails with the mentioned warning title. Interestingly, performing the same request in Postman (an API testing tool) yields a status of 200: OK, indicating that everything is functioning correctly and the data has been successfully stored in the database. However, I am unable to replicate this success within my web application by utilizing the following code:

  register(){

let details = {
  Serviceurl: this.serviceUrl,
  CompanyName: this.companyName,
  CompanyFullName: this.companyFullName,
  LanguageCulture: this.languageCulture,
  IsNewUser: this.isNewUser,
  User: {
    UserName: this.userName,
    FirstName: this.firstName,
    LastName: this.lastName,
    Email: this.email,
    Password: Md5.hashStr(this.password)
  }
}

this.authService.createAccount(details)
.then((result) => {

}, (err) => {

});
}

Subsequently, here is the actual request being made within my authService:

  createAccount(details){

return new Promise((resolve, reject) => {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post('http://SITEADDRESS/api/IM_Customers/CreateNew', JSON.stringify(details), {headers: headers})
      .subscribe(res => {
        let data = res.json();
        resolve(data);

      }, (err) => {
        reject(err);
      });

});

}

Answer №1

To resolve the access control issue in your API project, you should activate No-Access-Control-Allow-Origin feature. Inside the startup.cs file of the API Project, add the following code:

public void Configure(IApplicationBuilder app){
    app.UseCors(builder=>builder.AllowOrigin().AllowAnyMethod().AllowAnyHeader());
}

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 does my express POST request result in an empty req.body in Node.js?

After confirming that my data is being passed correctly and the db connection is successful, I am facing an issue with my ajax request. Even though the success callback returns the id, my data seems to not be passing through properly. When attempting to a ...

There has been an error of type TypeError, as the property 'replace' cannot be read from a null value

I encountered a TypeError message, even though my application seems to be functioning properly. "ERROR TypeError: Cannot read property 'replace' of null" I'm struggling to understand how to fix this issue. Can someone provide me ...

How to initiate a refresh in a React.js component?

I created a basic todo app using React, TypeScript, and Node. Below is the main component: import * as React from "react" import {forwardRef, useCallback, useEffect} from "react" import {ITodo} from "../types/type.todo" import ...

Ensure that the dropdown remains open at all times when using the angular2-multiselect-dropdown package

I am currently implementing the angular2-multiselect-dropdown in my Angular application. This dropdown is being used within a popup. What I am trying to achieve is that when a button is clicked, the popup should display the dropdown in an open mode witho ...

Discover the power of catching Custom DOM Events in Angular

When working with an Angular library, I encountered a situation where a component within the library dispatches CustomEvents using code like the following: const domEvent = new CustomEvent('unselect', { bubbles: true }); this.elementRef.nati ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

transform array elements into an object

I encountered the following code snippet: const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map( (cssClass) => { return { [cssClass]: true }; } ); This code block generates an array of objects like ...

Using TypeScript, apply an event to every element within an array of elements through iteration

I have written the code snippet below, however I am encountering an issue where every element alerts the index of the last iteration. For instance, if there are 24 items in the elements array, each element will alert "Changed row 23" on change. I underst ...

The interface 'HTMLIonIconElement' is not able to extend both 'IonIcon' and 'HTMLStencilElement' types at the same time

After upgrading my Angular Ionic app to use Angular v13 from Angular 12 with the command ng update, I encountered errors preventing me from running the application successfully. [ng] Error: node_modules/ionicons/dist/types/components.d.ts:66:15 - error TS2 ...

Setting base URLs for production and development in Angular 6: A step-by-step guide

As a beginner in Angular, I am looking for a way to set different base URLs for production and development environments. I aim to dynamically configure the base URL to avoid hard-coding it in the index.html file every time I switch between these two enviro ...

Experiencing an issue with mui/material grid causing errors

An error occurred in the file Grid2.js within node_modules/@mui/material/Unstable_Grid2. The export 'createGrid' (imported as 'createGrid2') could not be found in '@mui/system/Unstable_Grid' as the module has no exports. Desp ...

Handlebar files are not compatible with Typescript loading capabilities

I am encountering an issue with my directory structure as follows : src |- server |- myServer.ts |- views |- myView.hbs dist |- server |- myServer.js The problem lies in the fact that the dist folder does not have a views subfolder, where the J ...

What are some ways to enhance the design of Material Input Text boxes and make them more compact?

I have been developing an Angular application using Material UI v7, but I am finding that the input controls are not as compact as I would like them to be. I have attempted to customize them without success. Can someone provide guidance on how to achieve m ...

Leveraging the @Input Decorator in Angular 2

Check out the Angular 2 component code sample below @Component({ selector: 'author-edit', templateUrl:'./author/edit' }) export class AuthorEditComponent implements OnInit{ @Input() author: AuthorModel; fg: FormGroup; c ...

Checking the validity of an HTTP response using Python

I am currently in the process of creating a basic web server and I have written a Python function to handle requests. Here is what it looks like: def handle_request(client_connection): request = client_connection.recv(1024) print(request.decode()) ...

What is the best method for determining the color of the active angular theme for a particular component, such as the hover background of a button?

When using Angular 7 and material design to display a list, I encountered an issue with hover colors. The preset $primary, $accent, and $warn colors were not working well for this purpose. I wanted the hover color of the list items to match that of a butto ...

Having trouble applying [formControl] to a set of radio buttons in Angular2

Currently, I am encountering an issue with a list of groups of radio buttons in Angular2. My objective is to bind the value of each group of radio buttons using [formControl]. However, when implementing this, the radio buttons seem to lose their normal mut ...

Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of whe ...

Identify the locality and apply it to the root module of Angular 2 by utilizing a provider

I am working on a function that detects the current locale and I need to set it in the root App module of Angular 2 using a provider so that I can access it in all other components. I understand that I can achieve this by following the code below: { pr ...

Can a React function component be typed with TypeScript without the need for arrow functions?

Here is my current React component typed in a specific way: import React, { FunctionComponent } from "react"; const HelloWorld : FunctionComponent = () => { return ( <div> Hello </div> ); } export default HelloWorld; I ...