0

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:

enter image description here

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.
Tarta
  • 1,729
  • 1
  • 29
  • 63
  • What happens if you open http://localhost:44383//api/employees directly in a browser? – sideshowbarker Apr 11 '20 at 00:15
  • @sideshowbarker 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. – Tarta Apr 11 '20 at 07:51
  • What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it is 4xx or 5xx error rather than a 200 OK success response? – sideshowbarker Apr 11 '20 at 08:12
  • @sideshowbarker updated the question with the whole Configure and ConfigureServices method. Also the answer code is "(failed)" in the Network tab – Tarta Apr 11 '20 at 08:20
  • Whenever you have a problem with frontend JavaScript code and you post a question about it here, you really really want to always paste in — as text — the exact error messages the browser is logging in the devtools console. All of them. That can save a massive amount of time for you and for everybody else here who tries to help find an answer for the question. – sideshowbarker Apr 11 '20 at 08:28
  • @sideshowbarker wait.. that question doesn't solve my problem, I added the header in the request from the frontend as a possible solution, true, but by removing it I go back to the original error. Screenshot in the last edit of the question – Tarta Apr 11 '20 at 08:30
  • Do not paste in screenshots of error messages. Paste them in as text. Screenshots of error messages are not going to get indexed by search engines. Text will get indexed by search engines. – sideshowbarker Apr 11 '20 at 08:34
  • Whatever behavior happens when the Access-Control-Allow-Origin header is specified in the request is irrelevant — because it’s not a request header. So specifying it as a request header is an error, and the answer to any question about what happens when you specify it as a request header is the same: Don’t specify Access-Control-Allow-Origin as a request header. – sideshowbarker Apr 11 '20 at 08:37
  • @sideshowbarker understood.. thank you. I specified it hoping to solve the original problem. I won't anymore, but the main problem stays now: server side is not allowing CORS yet – Tarta Apr 11 '20 at 08:39

2 Answers2

1

this is not an issue with enabling CORS. You do not need it in this case. This is because you have a project created with the React boilerplate and what this means is that CORS is not required.

Steps to fix:

Remove all CORS related code from Startup.cs file.
In Configure method, you could add app.MapControllerRoute() to

app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action=Index}/{id?}");
        endpoints.MapControllerRoute();
    });

Change the following:

return axios.get(`${process.env.REACT_APP_SERVER_URL}/${endpoint}`, {
  headers: {
    'Access-Control-Allow-Origin': '*',
  }
});

To this:

return axios.get(`${endpoint}`);

When you do this, your app should just work.

codejockie
  • 9,020
  • 4
  • 40
  • 46
0

Make sure you also annotate your endpoint method with the [EnableCors] attribute:

[EnableCors]
public string Employees()
{
}

If it stills not working you can also try this config:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("*")
                                        .AllowAnyHeader()
                                        .AllowAnyMethod();
                });

        });

    }
Enrique Olvera
  • 134
  • 1
  • 4
  • still nothing unfortunately in both cases – Tarta Apr 10 '20 at 22:05
  • perhaps you could also upload your code for the controller action? – Enrique Olvera Apr 10 '20 at 22:07
  • Done.. by calling the endpoint through Postman I receive this though : <> – Tarta Apr 10 '20 at 22:10
  • Mmm seems like the middleware setup was done incorrectly, perhaps is an order specification thing, regardless, you can compare with the basic config I use whenever I need to enable a WebAPI with cors, perhaps it will help https://gist.github.com/kdev29/48e95fd38eb56265d3209d2a92343ad5 – Enrique Olvera Apr 10 '20 at 22:26
  • did exactly as in your example.. unfortunately still nothing :/ – Tarta Apr 10 '20 at 22:42