为了账号安全,请及时绑定邮箱和手机立即绑定

CORS 策略已阻止从源“null”在“https://localhost:44395”处提取

CORS 策略已阻止从源“null”在“https://localhost:44395”处提取

牧羊人nacy 2024-01-18 09:50:37
我有 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 代码中遵循以下内容:启动.csprivate 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.}尽管如此,我还是遇到了同样的错误。我的 Fetch 代码是:示例.jsasync 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));}这是一个非常常见的问题,但我仍然无法解决。请帮忙。编辑:请建议两种类型的URL。因为我还在主服务器上部署了这个 Web API,所以从服务器 URL 访问也会出现相同的错误。http://https://
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

此 url 在https://localhost:44395

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

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

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

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


查看完整回答
反对 回复 2024-01-18
  • 1 回答
  • 0 关注
  • 33 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信