简体   繁体   中英

React + ASP.Net-Core CORS Problems

While CORS is a big issue when working ReactJS in combination with ASP.Net-Core I figured out how to enable CORS so when accessing my UI ( http://localhost:3000 ) which uses SignalR/REST-Calls against the API ( http://localhost:51761 ).

Here the 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(); });
            }

On my React Application I am doing the following API call:

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

Opening the UI via Browser with URL http://10.65.1.23:3000 works fine. Doing a request against the API results into following error.

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

It makes sense that calling localhost:51761 wouldnt work because the browser is trying to call the API on the browsers machine.

When debugging the server code on the inner function of SetIsOriginAllowed I recognized that the origin will always be evaluated everytime I do a request when using the UI on my dev-machine ( localhost ) but never when using a different machine.

Did I missunderstood CORS or did a wrong setup? Thanks for your help!

while configuring, you need to mention the port number with URL.

In Startup.cs

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

Also, specify at the controller level

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

I figured out the problem by myself.

So actually what you need to do is to set the proxy in your react projects package.json to the URL of the API. In addition you need to make your http-request be dynamically and set the content-type of the request to non- text/html

So changing the client-code from

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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