Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I solve CORS Policy error with .NET 6 and React?

I am trying to call an API in the frontend, but I get this error instead:

Access to XMLHttpRequest at 'http://localhost:5087/api/GetPlayerById/2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • Frontend is running on http://localhost:3000/ (React)

  • Backend is running on http://localhost:5087/ (.NET 6)

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • API works on Postman

  • API works on browser (Copy/Pasting the API on browser)

  • CORS error appears when I call the API in React

I already looked at many post on CORS policy but none seems to help me. My last attemp was referring to Enable Cross-Origin Requests (CORS) in ASP.NET Core.

Code so far (in .NET 6):

Program.cs

using tournament_manager_backend.Data;
using Microsoft.EntityFrameworkCore;

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      policy =>
                      {
                          policy.WithOrigins("http://localhost:3000");
                      });
});

builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddScoped<IPlayerRepository, PlayerRepository>();
builder.Services.AddScoped<IMatchRepository, MatchRepository>();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "server=(localdb)\\ProjectModels;database=TournamentManager"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Host": {
    "CORS": "http://localhost:5087,http://localhost:3000"
  }
}

launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:19870",
      "sslPort": 44328
    }
  },
  "profiles": {
    "tournament_manager_backend": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5087",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }
  }
}

I know there are a lot of questions on this topic already but I have already changed the code many times from different sources that if I were to refer them here, it will make this post too long. I did the best I can to give you as much details as possible so that I can seek effective guidance. I will appreciate anyone helping. Thanks!

>Solution :

The easiest solution is to include a proxy in the React server that you’re using for development. In your package.json include:

"proxy": "http://localhost:5087/",

as part of the top level parameters (i.e., no parent). This creates a proxy through http://localhost:3000/ to your back end.

Note that this is for development. When you move to a "real" server you won’t be using the React dev server for serving your front end code and there will likely be a different way to setup CORS.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading