不存在“ Access-Control-Allow-Origin”标头。 XmlHttpRequest

时间:2019-03-25 12:50:13

标签: javascript asp.net-core cors xmlhttprequest

我有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。只需直接使用后端即可。

1 个答案:

答案 0 :(得分:0)

  1. 安装CORS nuget软件包。  
    Install-Package Microsoft.AspNetCore.Cors
  2. 在ConfigureServices中添加CORS服务

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

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