繁体   English   中英

React + ASP.Net-Core CORS 问题

[英]React + ASP.Net-Core CORS Problems

虽然在将 ReactJS 与 ASP.Net-Core 结合使用时,CORS 是一个大问题,但我想出了如何启用 CORS,因此在访问我的 UI( http://localhost:3000 )时,它使用 SignalR/REST-Calls 针对 API( http://localhost:51761 )。

这里是Startup.cs

      public void ConfigureServices(IServiceCollection services)
            {
                services.AddCors(option =>
                {
                    option.AddPolicy("myCors",
                        builder =>
                        {
                            builder.AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed(origin =>
                            {
                                if (origin.StartsWith("http://localhost")) return true;
                                if (origin.StartsWith("http://vdedarh02331")) return true;
                                if (origin.StartsWith("http://10.65.1.23")) return true;
                                return false;
                            });
                        });
                });
                services.AddControllers();
                services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "SimpleAPI", Version = "v1"}); });
            }
    
     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseSwagger();
                    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SimpleAPI v1"));
                }
                app.UseHttpsRedirection();
                app.UseRouting();
                app.UseCors("myCors");
                
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
            }

在我的 React 应用程序中,我正在执行以下 API 调用:

    axios
      .post("http://localhost:51761/Simple/Login")
      .then((response) => console.log(response))
      .catch((error) => {
        console.error(error);
        console.log("Trying to use IP");
        axios
          .post("10.65.1.23:51761/Simple/Login")
          .then((resp) => console.log(resp))
          .catch((err) => console.error(err));
      });

通过浏览器使用 URL http://10.65.1.23:3000打开 UI 可以正常工作。 对 API 发出请求会导致以下错误。

通过与 localhost 不同的机器上的 UI 调用 API

调用localhost:51761是有道理的,因为浏览器正在尝试调用浏览器机器上的 API。

在调试SetIsOriginAllowed的内部函数上的服务器代码时,我认识到在我的开发机器( localhost )上使用 UI 时,每次我发出请求时总是会评估原点,但在使用不同的机器时永远不会。

我是否误解了 CORS 或设置错误? 谢谢你的帮助!

在配置时,您需要在 URL 中提及端口号。

Startup.cs

builder =>
        {
            builder.WithOrigins("http://localhost:51761")
                                .AllowAnyHeader()
                                .AllowAnyMethod();
        });

此外,在控制器级别指定

[EnableCors("MyPolicy")]
public class SimpleController : Controller

我自己解决了这个问题。

所以实际上你需要做的就是将你的 react 项目package.json中的代理设置为 API 的 URL。 此外,您需要使您的 http-request 是动态的,并将请求的内容类型设置为非text/html

所以改变客户端代码

axios
      .post("http://localhost:51761/Simple/Login")
      .then((response) => console.log(response))
      .catch((error) => {
        console.error(error);
        console.log("Trying to use IP");
        axios
          .post("10.65.1.23:51761/Simple/Login")
          .then((resp) => console.log(resp))
          .catch((err) => console.error(err));
      });

    axios
      .post(
        "/Simple/Login",
        {},
        { headers: { "Content-Type": "application/json" } }
      )
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.error(error);
        console.log("Trying to use IP");
        axios
          .post(
            "/Simple/Login",
            {},
            { headers: { "Content-Type": "application/json" } }
          )
          .then((resp) => {
            console.log(resp);
          })
          .catch((err) => console.error(err));
      });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM