C#C
C#17mo ago
Kroros

Trouble enabling CORS

I'm building a website whose frontend is in React, and whose backend is in ASP.NET. I am currently trying to test sending a GET request from the frontend to be handled by the backend, but sending the request gives me the error in the picture.
I have tried fixing it using the method outlined here: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-8.0#cors-with-named-policy-and-middleware
but I still get the same error.

My Program.cs file:

using gaussBackend.Data;
using gaussBackend.Endpoints;

var MyAllowSpecificOrigin = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

var connString = builder.Configuration.GetConnectionString("CommentSection");
builder.Services.AddSqlite<CommentSectionContext>(connString);

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

builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigin);

app.UseAuthorization();

app.MapCommentsEndpoints();

await app.MigrateDbAsync();

app.Run();


The code I am using to send the request:
function get(page: number) {
  axios
    .get("http://localhost:5295/comments")
    .then((response) => {
      console.log(response.data);
      console.log(page);
    })
    .catch((error) => {
      console.error(error);
    });
}
image.png
Learn how CORS as a standard for allowing or rejecting cross-origin requests in an ASP.NET Core app.
Was this page helpful?