Home > front end >  Requesting to api domain from localhost
Requesting to api domain from localhost

Time:12-27

We are building an e-commerce website using React as our front-end framework and Dotnet for the backend. We want to hire some remote developers to work on the frontend project but we don't want to give them the whole backend project. We figured we should upload the API to our domain and then set the frontend to connect to it. The problem is we can't send requests to the API domain because of the same-origin policy. We tried to use CORS but because credentials are being sent throw responses, we have to specify the exact domain that can connect to the API. Since the computers which run the frontend on their localhost don't have a static IP, we can't do such a thing. I tried chrome plugins for passing CORS but they didn't work. Is there any way to fix this problem?

Here is the code I used in the Dotnet project:

app.UseCors(x => x 
            .WithOrigins("https://localhost:3000")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());

and I get this error in my console when I try to log in:

Access to fetch at 'https://api.paykanpars.com/api/user/login' from origin 'http://localhost:3000' 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.

Edit: I figured the server returns a 404 status in the response of preflight request. This only happends when I upload the backend to the server.

CodePudding user response:

Try to use this syntax

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("AllowAnyOrigin",
                      builder =>
                       {
                       builder.AllowAnyOrigin()
                              .AllowAnyMethod()
                              .AllowAnyHeader();
              }));

        .....
            
        }

        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            .....

           // app.UseRouting();

            app.UseCors("AllowAnyOrigin");

         //  app.UseAuthorization();
         // app.UseEndpoints(..
 
         }

Make sure that UseCors should be in the end of Configure method but before UseAuthorizaton. AddCors should be at the top of Configure services.

if only it works then you can replace

  builder.AllowAnyOrigin()

with

  builder.WithOrigins("https://localhost:3000")

CodePudding user response:

Try

app.use(cors()) 

for simplicity and see if it works. Then you can try specific configs later on if needed.

  • Related