Home > Net >  .NET API returns 404 response to preflight requests
.NET API returns 404 response to preflight requests

Time:12-28

I want to upload a .NET web API to a domain and then set the frontend to connect to it. The problem is I can't send requests to the API domain because of the same-origin policy. I tried to use CORS and allow all origins but because credentials are being sent through responses, I have to specify the exact domain that can connect to the API.

Here is the code I used in the my backend 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.

This works fine when I run the API on localhost but when I run it on my production host, it returns a 404 status in response to the preflight requests. The production host uses Plesk as its web host.

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