Problem: 'http://localhost:44383//api/employees' from origin 'https://localhost:44372' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Tried solution in the server application:
in Startup.cs the ConfigureServices method looks like:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddCors();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
services.AddAutoMapper(typeof(Startup));
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Test",
Version = "v1",
Description = "Test Api"
});
});
services.Installer(Configuration);
services.AddTransient<IDbClient, DbClient>();
}
in Startup.cs at the Configure method looks like:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "Test");
});
app.UseGlobalExceptionHandler(x =>
{
x.ContentType = "application/json";
x.ResponseBody(_ => JsonConvert.SerializeObject(new
{
Message = "An error occurred whilst processing your request"
}));
});
app.Map("/error", x => x.Run(y => throw new Exception()));
}
In the frontend my call is:
return axios.get(`${process.env.REACT_APP_SERVER_URL}/${endpoint}`,
{
headers: {
'Access-Control-Allow-Origin': '*',
}
});
Problem still happening unfortunately..
EDIT:
Controller:
[ApiController]
[Route("[controller]")]
[EnableCors]
public class EmployeesController : Controller
{
public EmployeesController(IDbClient dbClient, IMapper mapper)
{
..
}
[EnableCors]
[HttpGet("/api/employees")]
public ActionResult GetEmployees()
{
try
{
...
}
catch (Exception e)
{
...;
}
}
}
EDIT:
so, after some hours of work I can reformulate a bit better the problem. My code works normally when I try to access the controllers from browser or postman. It is blocked from CORS when instead from my React client app I make a call with axios against the server. I don't want any CORS at all on my server side application and I am trying to allow everything.
Full error when header is specified in the request:
Error when no custom header is put in the request from the frontend:
Access to XMLHttpRequest at 'http://localhost:50365/api/employees' from origin 'https://localhost:44311' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.