微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CORS 策略阻止了从源“null”获取“https://localhost:44395”的访问权限

如何解决CORS 策略阻止了从源“null”获取“https://localhost:44395”的访问权限

我有Asp .net core 3 Web API。我正在使用 Fetch 调用 POST API 之一,然后收到以下错误

Access to fetch at 'https://localhost:44395/api/challengeresponse/Verify' from origin 'null' 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. If an opaque response serves your needs,set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Failed to load resource: net::ERR_Failed

所以我研究并尝试使用 Web API 代码

Startup.cs

private readonly string AllowedOriginPolicy = "_AllowedOriginPolicy";
public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(AllowedOriginPolicy,builder =>
                    {
                        var corsOrigins = new String[1] { "https://localhost:44395" };

                        builder.WithOrigins(corsOrigins).AllowCredentials().AllowAnyHeader().AllowAnyMethod();
                    });
            });

            services.AddControllers();
        }

public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
   app.UseCors(AllowedOriginPolicy); //at the end of the method.
}

我仍然遇到相同的错误

我的提取代码是:

sample.js

async function fetchdata(){
    let _data = {
        OriginalData: "coordinateid",Signature: "URL",Certificate: "introduction"
    }

    const response = await fetch('https://localhost:44395/api/challengeresponse/Verify',{
     credentials: 'include',method: "POST",body: JSON.stringify(_data),headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json()) 
.then(json => console.log(json))
.catch(err => console.log(err));
}

这是一个非常常见的问题,但我仍然无法解决。请帮忙。

编辑:请为 http://https:// 两种类型的 URL 提供建议。因为我也在主服务器上部署了这个web API,从服务器URL访问也出现同样的错误

解决方法

这个网址 https://localhost:44395

var corsOrigins = new String[1] { "https://localhost:44395" };

它应该是客户端的 url 。应该改成这样:

var corsOrigins = new String[1] { "[client url]" };

注意:无论您使用什么客户端,请确保它在服务器上运行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。