Asp.net Core:跨域请求被阻止

时间:2021-07-05 07:27:57

标签: reactjs asp.net-core fetch-api

我使用 react 作为前端,使用 asp.net core 作为后端。我正在为 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>();
        }

Configure 方法是:

 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");
            });
        }

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

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);
  };

这是我在 Brower 网络选项卡中得到的输出:

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试如下 在您的 ConfigureServices 方法中

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

并在您的配置方法中

app.UseCors("ClientPermission");

答案 1 :(得分:0)

在 localhost 请求的客户端使用 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)
    }
    
  };