0

From an ASP .NET Core web app I am trying to make a call to a Drupal web api using React.js, however I get the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '[my-drupal-api]' is therefore not allowed access.

I have tried adding the following to my Startup.cs:

services.AddCors(options =>
{
   options.AddPolicy("CorsPolicy",
   builder => builder.AllowAnyOrigin()
   .AllowAnyMethod()
   .AllowAnyHeader()
   .AllowCredentials());
});

app.UseCors("CorsPolicy");

and I still get the same error.

I am curious if there is another way to do this server-side, without react. Is there way a way to do an asynchronous partial view that will load the data returned from the Drupal web api, without delaying the load of the rest of the page?

Thanks!

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Primico
  • 2,143
  • 3
  • 24
  • 36

1 Answers1

0

Startup can be configured like this:

public class Startup
{
    public const string CorsPolicyName = "YourSiteCorsPolicyName";

    ...

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        var corsBuilder = new CorsPolicyBuilder();
        corsBuilder.AllowAnyHeader();
        corsBuilder.AllowAnyMethod();
        corsBuilder.AllowAnyOrigin();
        corsBuilder.AllowCredentials();

        services.AddCors(
            options =>
            {
                options.AddPolicy(CorsPolicyName, corsBuilder.Build());
            });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ...
        app.UseCors(CorsPolicyName);
    }
}

In your controllers you can mark with the defined constant:

[EnableCors( Startup.CorsPolicyName )]
public class YourController : Controller { 
    ...
}
Dmitry Pavlov
  • 30,789
  • 8
  • 97
  • 121
  • Thanks for the response. I still get the same error: Failed to load http://1.1.1.1/api/news: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:11111' is therefore not allowed access. – Primico Oct 11 '17 at 13:13
  • Do you get this issue when the app is hosted on real server rather than on you local machine? You might be interested to read this also https://stackoverflow.com/questions/44544425/getting-error-no-access-control-allow-origin-header-is-present-on-the-reques – Dmitry Pavlov Oct 11 '17 at 16:24