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

时间:2020-12-23 03:16:23

标签: javascript post cors fetch asp.net-core-webapi

我有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访问也出现同样的错误。

1 个答案:

答案 0 :(得分:1)

这个网址 https://localhost:44395

<块引用>

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

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

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

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