【问题标题】:No 'Access-Control-Allow-Origin' header is present. XmlHttpRequest不存在“Access-Control-Allow-Origin”标头。 XmlHttpRequest
【发布时间】:2019-08-15 17:15:50
【问题描述】:

我得到了 XmlHttpRequest 对象,我正在尝试将长 html 数据字符串发送到 Asp Net Core,以便从中提取内容 PDF 文件。但仍然获得 CORS 政策。即使我的标题中有“Access-Control-Allow-Origin”,这对我来说仍然是个问题。已经用 CORS 尝试了一切。为 Asp net Core 安装了 cors,没有任何改变。如果我使用本地的 HTML 文档,一切正常。

完全错误:

在“https://.../getInfoWindowPdf?”访问 XMLHttpRequest从 来源“https://...”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

function infoWindowPdf()
{
    // Create request
    let http = new XMLHttpRequest(); //XMLHttpRequest XDomainRequest
    let url = backend + "getInfoWindowPdf?";

    // Add in htmlContent header
    let htmlContent = "<style>" + style +"</style>";

    // Get needed content
    let infoWindow = document.querySelector("#section-library-modal");

    //Waits for backend to create file after all open it and remove created temporary files
    http.onreadystatechange = function()
    {
        if(http.readyState == 4)
        {
            window.open(backend + 'InfoPdf?filePath=C:\\Projects\\Web\\WebSections\\wkhtmltopdf\\bin\\pdf-export\\' + sectionName + ".pdf", '_blank');
            setTimeout(() => {getDBData('removepdf?filePath=C:\\Projects\\Web\\WebSections\\wkhtmltopdf\\bin\\pdf-export\\&filename=' + sectionName);}, 100);
        }
    };

    http.open("POST", url, true);
    http.setRequestHeader('Access-Control-Allow-Origin', '*');
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //application/x-www-form-urlencoded
    http.send(params);
}

我的用于 CORS 的 Asp Net Core 启动配置。

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

  public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins,
            builder =>
            {
                builder.WithOrigins("http://localhost:5000",
                                    "http://localhost:5000/websections/getInfoWindowPdf?"
                                    ).AllowAnyHeader().AllowAnyMethod();
            });
        });

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseCors(MyAllowSpecificOrigins);

        //app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

编辑: 如果您想向后端项目发送一些数据,甚至不要尝试使用 Xmlhttprequest。直接使用后端即可。

【问题讨论】:

  • 几天前我遇到了同样的问题。事实证明,这不是 CORS 问题;但这就是它的处理方式。就我而言,我还没有启动 asp.net 核心项目(是的,我有时就是这么笨)。
  • 别以为它是 CORS 以外的东西。如果我从本地打开 HTML 文件,我的按钮将起作用。但是如果从 Asp 打开相同的 HTML 则会出现此错误。
  • 您在 .net 核心应用程序中的 CORS 策略是什么?您应该在 startup.cs 中包含一些内容和/或设置您的策略的扩展。您的请求中不应包含任何内容,这不是必需的。
  • 编辑了我的帖子。
  • 您的错误消息,尽管您对它进行了截断,但显示您的来源以https:// 开头,但您允许的所有来源都以http:// 开头。您似乎只是在可接受的来源列表中打错了字。

标签: javascript asp.net-core cors xmlhttprequest


【解决方案1】:
  1. 安装 CORS nuget 包。
    Install-Package Microsoft.AspNetCore.Cors
  2. 在 ConfigureServices 中添加 CORS 服务

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddCors();
    }
    
  3. 在 Startup.cs 文件的配置方法中

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseCors(
            options => options.WithOrigins("http://example.com").AllowAnyMethod()
        );
        app.UseMvc();
    }

【讨论】:

  • 尝试了您的确切变体,即使我之前尝试过,仍然得到相同的错误。
  • 如果你使用 chrome,在发送请求后,你能看到网络选项卡中存在哪些请求/响应标头吗?
  • 等等,response tab什么都没有……而且根本没有response header,只有request header
猜你喜欢
  • 2015-11-18
  • 1970-01-01
  • 2018-10-28
  • 2017-02-21
  • 2015-09-28
  • 2016-10-30
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
相关资源
最近更新 更多