【问题标题】:Access to fetch at 'https://localhost:44395' from origin 'null' has been blocked by CORS policyCORS 策略已阻止从源“null”访问“https://localhost:44395”获取
【发布时间】:2021-04-01 17:44:39
【问题描述】:

我有 Asp .net core 3 网络 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.
}

不过,我还是遇到了同样的错误。

我的提取码是:

示例.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 访问也会出现同样的错误。

【问题讨论】:

  • origin null 建议不使用 http[s] 提供发出请求的页面
  • 从 html 页面运行的 javascript 文件是否也由本地服务器托管?如果你只是从本地浏览器打开文件,你会遇到一些麻烦
  • 是的,javascript 文件是从 HTML 文件运行的。

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


【解决方案1】:

这个网址https://localhost:44395

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

应该是客户的网址。应该改成这样:

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

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

【讨论】:

  • 在此更改之后,fetchdata() URL 也进行了相同的更改。现在出现错误:net::ERR_CONNECTION_REFUSED
  • @Varsh,该错误表示 url 找不到服务器。你用什么客户端?
  • 我不明白你在问什么,因为我对此不太方便。但是,我运行我的 Web API 项目,然后从普通的 javascript 文件调用它的 POST API,该文件从 Chrome 浏览器上的 HTML 页面获取调用。
  • @Varsh,这个javascript怎么运行,直接打开?您的客户地址是什么?
  • 你可以在webapi中使用builder.AllowAnyOrigin()这个方法,它将允许任何客户端。
猜你喜欢
  • 2021-12-30
  • 2020-07-29
  • 2021-07-20
  • 2020-09-17
  • 1970-01-01
  • 2021-01-20
  • 2017-06-17
  • 2021-03-08
  • 2020-11-11
相关资源
最近更新 更多