简体   繁体   中英

Enabling CORS in Google App Engine Flexible Environment

I am facing issues enabling CORS support for a ASP.NET CORE application that is hosted using Google App Engine and the flexible environment.

Every AJAX request using the axios library results in the following error...

Access to XMLHttpRequest at ' https://api.[something].services/request ' from origin ' http://localhost:8080 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here the configuration of CORS on the web api:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => 
    options.AddPolicy("MyPolicy", 
        builder =>
        {
            builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();
        }));

   // ...

   services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();

        System.Environment
              .SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
                          Path.Combine(Directory.GetCurrentDirectory(),
                          Configuration["GAE:Credentials"]));
    }
    else
    {
        app.UseHsts();
    }

    // ...

    app.UseCors("MyPolicy");
    app.UseHttpsRedirection();
    app.UseMvc();
}

This type of CORS errors are usually obtained when a resource1 does cross-origin HTTP requests to another resource2 without the handler for resource2 returning an Access-Control-Allow-Origin: response header containing the value http://resource1 .

With this in mind, the http header handler configuration needs to be appropriately set in the application App.yaml file which is deployed in App Engine. Most browsers use the XMLHttpRequest object to make a cross-domain request,taking care of inserting the right headers and handling the CORS interaction with the server.

All these information above apply to App Engine Standard and not the App Engine Flex environment. That is because CORS requests are disallowed by default on App Engine Flex . However you can allow CORS request by adding this "x-google-endpoints" to your API configuration documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM