I keep running into a CORS error with my React app every time I try to make a call to my API. The error message says "No 'Access-Control-Allow-Origin' header is present

I just started learning React and I'm currently working on setting up my login system to connect with my API. I am attempting to make a call from my React Redux app to my .NET Core (3.1) API. The React app is located at http://localhost:3000, while the API is at https://localhost:44383/ (not sure if this detail matters).

When making a POST request, I'm encountering a CORS error as shown below:

https://i.sstatic.net/NGboF.png


I don't believe the issue originates from the API because I have configured the cross-origin requests policy in my startup.cs ConfigureServices method (C#)

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader());

                options.AddPolicy(name: "react",
                  builder =>
                  {
                      builder.WithOrigins("http://localhost:3000/").WithHeaders(HeaderNames.AccessControlAllowOrigin, "http://localhost:3000"); ;
                  });
            });

and applied that policy within the configure method

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("react");

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseAuth();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

        }

Upon inspection using Postman, it is evident that the correct header is being attached: https://i.sstatic.net/q5oYs.png


While I'm not as experienced with React, here are the relevant parts of my authentication process including the API call with headers:

loginEffect() function of AuthSaga.ts (React/Typescript)

export function* loginEffect(action: any) {
  console.log("loginEffect", action)

  try {
    const data = {
      headers: {
        "content-type": "application/json",
        "Access-Control-Allow-Origin": "http://localhost:3000/"
      },
      body: {
        ...action.payload,
      },
    }

    const { timeoutDelay, response } = yield race({
      timeoutDelay: delay(10000),
      response: call(AuthAPI.postLogin, data),
    })

    if (timeoutDelay) {
      yield put(setAuthFailure("Server timed out"))
    }

    if (response) {
      if (response.status === 200) {
        console.log("200");
        const responseJson = yield response.json()
        yield put(loginSuccess(responseJson))
      } else {
        console.log("fail");
        const responseJson = yield response.json()
        yield put(setAuthFailure(responseJson))
      }
    }
  } catch (error) {
    yield put(setAuthFailure("Something went wrong. Try again later."))
  }
}

login.tsx

export const Login: React.FC = (props) => {
  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const dispatch = useDispatch()

  const handleSubmit = () => {
    dispatch(login({ UserName: username, Password: password }))
  }

  return (
    <PageWrapper>
      <LoginWrapper>
        <input
          placeholder="Username"
          onChange={(e) => setUsername(e.target.value)}
        ></input>
        <input
          placeholder="Password"
          onChange={(e) => setPassword(e.target.value)}
        ></input>
      </LoginWrapper>
      <button onClick={handleSubmit}>Submit</button>
    </PageWrapper>
  )
}

and AuthAPI.ts

export const AuthAPI: AuthAPIInterface = {
    async postLogin(data: any): Promise<object> {
        const postLoginUrl: string = `${ baseApi.authUrl }/login`
        console.log('[URL FOR postLogin]', postLoginUrl);
        console.log(data);


        return fetch(postLoginUrl, {
            method: 'POST',
            headers: data.headers,
            credentials: 'include',
            body: JSON.stringify(data.body)
        })
    },
    async postRegister(data: any): Promise<object> {
        const postRegisterUrl: string = `${ baseApi.authUrl }/register`
        console.log('[URL FOR postRegister]', postRegisterUrl);

        return fetch(postRegisterUrl, {
            method: 'POST',
            headers: data.headers,
            credentials: 'include',
            body: JSON.stringify(data.body)
        })
    }

Answer №1

An issue has been identified in your code:

builder.WithOrigins("http://localhost:3000/").WithHeaders(HeaderNames.AccessControlAllowOrigin, "http://localhost:3000"); 

Please remove the trailing "/" from the origins:

builder.WithOrigins("http://localhost:3000")

Additionally, ensure you are utilizing all headers and methods as follows:

options.AddPolicy(name: "react",
                  builder =>
                  {
                      builder.WithOrigins("http://localhost:3000")
                   .AllowAnyMethod()
                   .AllowAnyHeader());
                  });

If you have multiple policies, make sure to include the CORS policy name in your controller action. To start, consider removing or commenting out the "AllowAll" policy in your startup file.

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

Retrieve the MainPage using the IServiceProvider within the context of a Microsoft.Maui.Controls.Application

I recently started a new dotnet maui project and I'm looking to resolve MainPage from IServiceProvider. In my MauiProgram.cs, I included the line builder.Services.AddSingleton<MainPage>(); in place of (App.xaml.cs): public partial class App ...

What are the steps to integrate FabricJs into a TypeScript project?

Recently started learning JavaScript and I am interested in rotating, changing scale of images on canvas and coding in TypeScript using Fabric.js. As the import method for TypeScript differs from JavaScript, I am looking for guidance on how to import it in ...

Is it not allowed to view the WCF svc file?

Currently, I am working with a WCF project in VS2010 + C# + .Net 4.0 + IIS 7.5 + Windows 7. Whenever I attempt to open an svc file (by right-clicking the svc file in IIS manager and selecting browse) in IIS, I encounter the following error message. Can any ...

Examining build errors within a solution build is crucial, as any errors detected within an SQL file will cause the entire build to fail

In my current c# project, I have a console application that utilizes DbUp to execute scripts in a SQL Server database. I am trying to find a way to halt the build process if there are any syntax errors in the .sql file being utilized. I have attempted var ...

The SonarTsPlugin report is coming back clean with no issues found in the Typescript files

In my current project, I am attempting to analyze an Angular application using SonarQube. This particular project consists of a mix of JavaScript and TypeScript files. During the Sonar analysis process, I have noticed that while issues are being generated ...

Searching for two variables in an API using TypeScript pipes

I'm stuck and can't seem to figure out how to pass 2 variables using the approach I have, which involves some rxjs. The issue lies with my search functionality for a navigation app where users input 'from' and 'to' locations i ...

When attempting to start the MediaRecorder, an illegal state exception is thrown in Java, causing an

I am encountering a problem while using the MediaRecorder in Android Xamarin. Whenever I attempt to start or stop a recording, I am presented with the following exception: 07-15 21:06:40.984 W/System.err(13609): java.lang.IllegalStateException 07-15 21:06 ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

Angular Fails to Identify Chart.js Plugin as an Options Attribute

Encountering issues with using the 'dragData' plugin in Chart.js 2.9.3 within an Angular environment: https://github.com/chrispahm/chartjs-plugin-dragdata After importing the plugin: chartjs-plugin-dragdata, I added dragdata to the options as sh ...

Ensuring full enum coverage in TypeScript switch/case statements

I have 2 enums Color and Shape. The constant SHAPES_BY_COLOR connects shapes with different colors. In the future, I aim to execute specific actions depending on the selected color and shape using a switch/case statement. Is there a way for TypeScript to ...

Efficient Searching with Typescript and Lodash: Boosting Performance with Arrays and Objects

I am faced with the challenge of converting between two classes called MyObject and MyObjectJSON, which have helper methods to assist in the conversion process: myObj.toJSON() and MyObject.fromJSON(). Currently, I have instances of these classes represent ...

What is the process for transforming a key-value object from JavaScript to TypeScript?

I am currently facing a challenge in converting a JavaScript object into a TypeScript version as part of our code refactoring process :( I am struggling to figure out how to properly migrate a JS JSON object into a correct TS format. For instance, consider ...

What could be causing the SQL query to return a value of 1 when using select scope_identity()?

I've been working on a SQL query that involves using SELECT SCOPE_IDENTITY() in sqlcommand. Here is an example of my code: SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Supplier(Supplier_Name,Supplier_Address, Supplier_PhoneNo,Supplier_City,Suppl ...

While attempting to update the package.json file, I encountered an error related to the polyfills in Angular

I have been working on a project with ng2 and webpack, everything was running smoothly until I updated the package.json file. Since then, I have been encountering some errors. Can anyone please assist me in identifying the issue? Thank you for any help! P ...

Adjust the Viewer Criteria

I utilized the report viewer in my project (VS 2010 - asp.net with c#). The report viewer successfully retrieves data from the database, but I wanted to dynamically set the title. For this purpose, I added a parameter called "title" and linked it to a Text ...

What are the real-world applications of "Type-only Field Declarations"?

Source: Type-only Field Declarations. interface Animal { dateOfBirth: any; } interface Dog extends Animal { breed: any; } class AnimalHouse { resident: Animal; constructor(animal: Animal) { this.resident = animal; } } class DogHouse ext ...

Incorporating a custom transpiled file format into Typescript imports

I am trying to import a file format .xyz that does not have fixed types for all instances of the format: import { Comment, Article, User } from "./Blog.xyz" However, I keep getting this error message: TS2307: Cannot find module './Blog.xy ...

Deciphering the SessionProvider error: When "useSession" isn't recognized as a function

I recently started diving into React and NextJS, but I've been able to piece things together with the knowledge I have. Recently, I added social login functionality using Lucia auth and now I'm looking to implement a session provider to allow ac ...

Evaluating the initial value from an array for radio buttons in Angular using Typescript

I am trying to retrieve the first value from an array that I receive through a get request via an api. Below is my HTML code: <div class="row" class="select-options" *ngFor="let options of paymentOptions;let idx = index"&g ...

Establishing a default value for a select field within a Redux form

Looking to display a default option that is not showing up, despite trying various solutions Tried searching online for a fix but nothing seems to be working <Field name="product_group" component={renderSelectField} label='Product Group&ap ...