Varsh
Varsh

Reputation: 465

Access to fetch at 'https://localhost:44395' from origin 'null' has been blocked by CORS policy

I have Asp .net core 3 web API. I am calling one of the POST API using Fetch then getting the following errors:

Access to fetch at 'https://localhost:44395/api/challengeresponse/Verify' from origin 'null' 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.
Failed to load resource: net::ERR_FAILED

So I research and try following in Web API code:

Startup.cs

private readonly string AllowedOriginPolicy = "_AllowedOriginPolicy";
public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(AllowedOriginPolicy,
                    builder =>
                    {
                        var corsOrigins = new String[1] { "https://localhost:44395" };

                        builder.WithOrigins(corsOrigins).AllowCredentials().AllowAnyHeader().AllowAnyMethod();
                    });
            });

            services.AddControllers();
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   app.UseCors(AllowedOriginPolicy); //at the end of the method.
}

Still, I am getting the same errors.

My Fetch code is:

sample.js

async function fetchdata(){
    let _data = {
        OriginalData: "coordinateid",
        Signature: "URL",
        Certificate: "introduction"
    }

    const response = await fetch('https://localhost:44395/api/challengeresponse/Verify', {
     credentials: 'include',
     method: "POST",
     body: JSON.stringify(_data),
     headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json()) 
.then(json => console.log(json))
.catch(err => console.log(err));
}

It is a very common question but still, I am not able to solve. Please help.

Edit: Please suggest for http:// and https:// both type of URL's. Because I also deployed this web API on the main server, and accessing from server URL also gives the same error.

Upvotes: 0

Views: 2140

Answers (1)

Karney.
Karney.

Reputation: 5031

This url https://localhost:44395 in

var corsOrigins = new String[1] { "https://localhost:44395" };

It should the client's url . It should be changed to be like this:

var corsOrigins = new String[1] { "[client url]" };

Note: No matter what client you use, please make sure it runs on a server.

Upvotes: 1

Related Questions