'React + ASP.Net-Core CORS Problems

While CORS is a big issue when working ReactJS in combination with ASP.Net-Core I figured out how to enable CORS so when accessing my UI (http://localhost:3000) which uses SignalR/REST-Calls against the API (http://localhost:51761).

Here the Startup.cs

      public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(option =>
                {
                    option.AddPolicy("myCors",
                        builder =>
                        {
                            builder.AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed(origin =>
                            {
                                if (origin.StartsWith("http://localhost")) return true;
                                if (origin.StartsWith("http://vdedarh02331")) return true;
                                if (origin.StartsWith("http://10.65.1.23")) return true;
                                return false;
                            });
                        });
                });
                services.AddControllers();
                services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "SimpleAPI", Version = "v1"}); });
            }
    
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseSwagger();
                    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SimpleAPI v1"));
                }
                app.UseHttpsRedirection();
                app.UseRouting();
                app.UseCors("myCors");
                
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
            }

On my React Application I am doing the following API call:

    axios
      .post("http://localhost:51761/Simple/Login")
      .then((response) => console.log(response))
      .catch((error) => {
        console.error(error);
        console.log("Trying to use IP");
        axios
          .post("10.65.1.23:51761/Simple/Login")
          .then((resp) => console.log(resp))
          .catch((err) => console.error(err));
      });

Opening the UI via Browser with URL http://10.65.1.23:3000 works fine. Doing a request against the API results into following error.

Calling the API though UI on different machine than localhost

It makes sense that calling localhost:51761 wouldnt work because the browser is trying to call the API on the browsers machine.

When debugging the server code on the inner function of SetIsOriginAllowed I recognized that the origin will always be evaluated everytime I do a request when using the UI on my dev-machine (localhost) but never when using a different machine.

Did I missunderstood CORS or did a wrong setup? Thanks for your help!



Solution 1:[1]

I figured out the problem by myself.

So actually what you need to do is to set the proxy in your react projects package.json to the URL of the API. In addition you need to make your http-request be dynamically and set the content-type of the request to non-text/html

So changing the client-code from

axios
      .post("http://localhost:51761/Simple/Login")
      .then((response) => console.log(response))
      .catch((error) => {
        console.error(error);
        console.log("Trying to use IP");
        axios
          .post("10.65.1.23:51761/Simple/Login")
          .then((resp) => console.log(resp))
          .catch((err) => console.error(err));
      });

to

    axios
      .post(
        "/Simple/Login",
        {},
        { headers: { "Content-Type": "application/json" } }
      )
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.error(error);
        console.log("Trying to use IP");
        axios
          .post(
            "/Simple/Login",
            {},
            { headers: { "Content-Type": "application/json" } }
          )
          .then((resp) => {
            console.log(resp);
          })
          .catch((err) => console.error(err));
      });

Solution 2:[2]

while configuring, you need to mention the port number with URL.

In Startup.cs

builder =>
        {
            builder.WithOrigins("http://localhost:51761")
                                .AllowAnyHeader()
                                .AllowAnyMethod();
        });

Also, specify at the controller level

[EnableCors("MyPolicy")]
public class SimpleController : Controller

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dpa
Solution 2 Ajay Gupta