威势网络,为您的企业和团队注入互联网活力!
服务热线:138-9741-0341

Ensure CORS response header values are valid

发布日期:2022/8/29 作者: 浏览:1361

网站上线后,后台捕获到很多404错误,同时打开前台,看到以下浏览器报警信息。

Ensure CORS response header values are valid

A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request .
To fix this issue, ensure the response to the CORS request and/or the associated preflight request are not missing headers and use valid header values.

Note that if an opaque response is sufficient, the request's mode can be set to no-cors to fetch the resource with CORS disabled; that way CORS headers are not required but the response content is inaccessible (opaque)


        一、CORE原理:在服务器响应报文头中通过access-control-allow-orgin告诉浏览器允许跨域访问的域名。

     参考地址:https://web.dev/cross-origin-resource-sharing/?utm_source=devtools

       二、解决方案:

    3.1的在


       public void ConfigureServices(IServiceCollection services)
        {

            //解决 Ensure CORS response header values are valid 问题
            services.AddCors(opt => {

                opt.AddDefaultPolicy(b =>
                {
                    //允许哪些域名访问
                    b.WithOrigins(new string[] { "http://www.qhwins.com:3000" })
                    //AllowAnyOrgin()  接收所有的url
                    //AllowAnyMethod() 接受所有的传输方式
                    //AllowAnyHeader() 接受所有的报文头
                    //AllowCredentials() 接收所有的认证方式
                    .AllowAnyMethod().AllowAnyHeader().AllowCredentials();
                });

                });
        } 

然后


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLeftTime)
        {
            
                 app.UseCors();//解决 Ensure CORS response header values are valid 问题

        }


6.0的

        1、在var app=builder.Build()前写入


                builder.Services.AddCors(opt=>{

                        opt.AddDefaultPolicy(b=>{

                                //允许哪些域名访问

                                b.WithOrigins(new string[]{"http://localhost:3000"})

                                 //AllowAnyOrgin()  接收所有的url

                                //AllowAnyMethod() 接受所有的传输方式

                                //AllowAnyHeader() 接受所有的报文头

                                //AllowCredentials() 接收所有的认证方式

                                .AllowAnyMethod().AllowAnyHeader().AllowCredentials();

                        })

                })

        2、在Program.cs的app.UseHttpsRedirection()这句代码之前增加一行
            app.UseCors();

官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-6.0


下拉加载更多评论
最新评论
暂无!