Asp.net 核心:跨域请求被阻止

Asp.net Core: Cross-Origin Request Blocked

我使用 React 作为前端,asp.net 核心作为后端。我正在为 API 请求使用 fetch API 但我在浏览器控制台上收到 Cors 错误消息:跨源请求被阻止:同源策略不允许读取位于 https://localhost 的远程资源: 44316/api/auth/register。 (原因:CORS请求没有成功)。

我的 ConfigureServices 方法是:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("myPolicy", builder =>
                {
                    builder.WithOrigins("http://localhost:3000")
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                });
            });
            services.AddSignalR();
            services.AddDbContext<UserContext>(options => options.UseSqlServer(Configuration.GetConnectionString(name: "Default")));
            services.AddControllers();
            services.AddScoped<IUserRepository, UserRepository>();
            services.AddScoped<IJwtHelper, JwtHelper>();
        }

配置方法为:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseCors("myPolicy");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/chat");
            });
        }

在 React 中,我创建了一个表单提交事件,它看起来像:

const submitRegisterForm = async (e) => {
    e.preventDefault();
    await fetch(
      "https://localhost:44316/api/auth/register",{
        method: 'POST',
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({
          name,
          email,
          password,
          role,
        })
      });

    setRedirectTo(true);
  };

这是我在浏览器网络选项卡中获得的输出:

尝试如下 在您的 ConfigureServices 方法中

services.AddCors(options =>
            {
                options.AddPolicy("ClientPermission", policy =>
                {
                    policy.AllowAnyHeader()
                        .AllowAnyMethod()
                        .SetIsOriginAllowed(_ => true)
                        .AllowCredentials();
                });
            });

并在您的 Configure 方法中

app.UseCors("ClientPermission");

在本地主机请求的客户端使用 http 而不是 https

const submitRegisterForm = async (e) => {
    e.preventDefault();
    try {
        const res = await fetch(
      "http://localhost:44316/api/auth/register",{
        method: 'POST',
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({
          name,
          email,
          password,
          role,
        })
      });
       setRedirectTo(true);
    }
    catch(err){
      console.log(err)
    }
    
  };