不存在“ Access-Control-Allow-Origin”标头。 XmlHttpRequest [英] No 'Access-Control-Allow-Origin' header is present. XmlHttpRequest

查看:156
本文介绍了不存在“ Access-Control-Allow-Origin”标头。 XmlHttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有XmlHttpRequest对象,并且我正尝试将较长的html数据字符串发送到Asp Net Core,以使其包含PDF文件。但仍然获得CORS政策。尽管我的标题中有 Access-Control-Allow-Origin,但对我来说仍然是一个问题。已经尝试使用CORS进行所有操作。为asp net Core安装了cors,未做任何更改。如果我使用本地的HTML文档,则一切正常。

I got XmlHttpRequest object, and i'am trying to send long html data string to Asp Net Core, to make out of it content PDF file. But still getting CORS policies. Even-though i have "Access-Control-Allow-Origin" in my header, it still an issue for me. Already tried everything with CORS. Installed cors for Asp net Core, nothing changed. Everything works fine if i use my HTML document from local.

完全错误:


在'来源 https:// ...的https://.../getInfoWindowPdf rel = nofollow noreferrer> https://.../getInfoWindowPdf ?'已被阻止根据CORS政策:对
飞行前请求的响应未通过访问控制检查:所请求的
资源上没有
'Access-Control-Allow-Origin'标头。

Access to XMLHttpRequest at 'https://.../getInfoWindowPdf?' from origin 'https://...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.



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的My Asp Net Core启动配置。

My Asp Net Core Startup Config for CORS.

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,如果您想将一些数据发送到您的后端项目。只需直接使用后端即可。

Do not even try to work with Xmlhttprequest, if you want send some data to your backend project. Just use backend straight.

推荐答案


  1. 安装CORS nuget软件包。
  1. Install the CORS nuget package.
Install-Package Microsoft.AspNetCore.Cors


  • 在ConfigureServices中添加CORS服务

  • Add CORS services in ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddCors();
    }
    


  • 在Startup.cs文件的Configure方法中

  • In Configure method of Startup.cs file

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


  • 这篇关于不存在“ Access-Control-Allow-Origin”标头。 XmlHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆