[Vuejs]-Getting a CORS error when trying to communicate between vuejs frontend and .NET 6 backend locally

0👍

Thanks to MindSwipe for the actual answer!

For people with the same error this is what the final program.cs looked like:

using CrashService.Services.Interfaces;
using CrashService.Services.Implementations;

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

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "MyPolicy",
        policy =>
        {
            policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
        });
});
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ICrashService, CrashServices>();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseCors("MyPolicy");
app.UseAuthorization();

app.MapControllers();

app.Run();

Please mind that this solution is not really safe, as you allowing any header, method and origin.

A safer way is to actually add the correct origin:

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

Leave a comment