首页 > 解决方案 > 使用 safari 时仅在子页面中出现 Cors 错误

问题描述

仅使用 safari 时,我的网站在子页面中遇到 CORS 错误。意思是,在主页上,没有 CORS 错误,并且 api 在包括 safari 在内的所有浏览器上返回 200 和正确的 json 数据。但是当涉及到https://example.com/blog所有其他浏览器时,除了显示 CORS 错误的 safari 之外。

我的网站前端位于https://example.com,而我的 api 位于https://api.example.com/api

我已尝试按照此处对此问题的答案中的建议添加斜杠: CORS request not working in Safari

该 api 使用 asp dotnet core 进行编码,并使用 nginx 反向代理托管在 Debian 10 上,我假设它传递了正确的标头(知道它在主页中工作正常)。这是我添加 CORS 支持的代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
      options.AddPolicy("AllowAll",
         builder =>
         {
             builder.WithOrigins(Configuration.GetSection("Origins"))
                    .SetIsOriginAllowed(x=>_ = true)
                    .AllowCredentials()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .SetPreflightMaxAge(TimeSpan.FromMinutes(60)); //one hour preflight is ok
         }); 
    });
    //rest of the code
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseForwardedHeaders();
    app.UseHttpsRedirection();
    app.UseResponseCompression();
    app.UseRouting();
    app.UseCors("AllowAll");
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers().RequireCors("AllowAll");
    });
}

标签: .net-coresafaricorsnginx-reverse-proxy

解决方案


推荐阅读