Sudhir Jangam
Sudhir Jangam

Reputation: 776

Dot Net Core Web API with Javascript - CORS policy error

I am using Visual Studio code with liveserver for html/javascript, and using VS Studio 2019 for Dot net core Web API I have create site in IIS on Windows 10 locally for the web api.

  1. I have a login page , that accepts user id and password. This is coded in login.html

The login page has following javascript function, that is invoked on login button click event

function fnlogin() {
   window.location.href = "http://localhost:5500/productmenu.html"
}
  1. Once logged in, a menu page is displayed. This is coded in productmenu.html with following
<header>
   <ul class = "nav">
     <li class="navlink"> <a href="productInfo.html> target="content"> Product Information <a> <li?
     <li class="navlink"> <a href="orderHistory.html> target="content"> Order History <a> <li?
   </ul>
</header>
  1. Once user selects the menu option "Product Information", another html page is displayed This is coded in productinfo.html

  2. Once the user enters product code and clicks on search , a dot net core web api is invoked and data is displayed in the productinfo.html using fetch api

The api is called as follows in JS

fetch('http://localhost:8082/api/product/' + productId)
.then(response => response(json))
.then((response => {
    return response
})
.then ( (response) => {
    console.log(response);
   })
.catch(err => console.log(err));
  1. The dot net core web api has following in startup.cs
method : configureServices

services.AddDefaultPolicy(
   options.AddDefaultPolicy (
      builder => 
      {
           builder.WithOrigins("http://127.0.0.1:5500)
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials()
      })
)};

The configure method has following

app.UseRouting();
app.UseCors();
app.UseAuthorization():

The web api is published in IIS on site with port 8082

The issue is as follows

  1. When I test the web api in browser directly , it works properly
  2. When I run the productmenu.html in live server , a new browser window opens with the link 127.0.0.1:5500/productmenu.html and menu is displayed . Once I select the "Product Information" menu option, the page Product information page is dispalyed. Once I enter product id and click on search button , the web api is invoked and then the product information is displayed correctly. No issue..
  3. But when I run the login.html in VS code/live server, and navigate to the product information page using the same steps (as described in #2 ) and click on the search button, I get following CORS error in Chrome dev tools "Access to fetch at .. from origin ... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I checked the Network tab in Chrome dev tools and see Request headers

Accept: */*
Host: localhost:8082
Origin: http://localhost:5500
Sec-Fetch-Dest: Empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site : same-site

Upvotes: 1

Views: 1407

Answers (1)

Serge
Serge

Reputation: 43959

You have a bug in Cors syntax. This is a syntax for default policy:

 services.AddCors(options =>
        {
       options.AddDefaultPolicy(
         builder => 
      {
           builder.WithOrigins("http://127.0.0.1:5500")
            .AllowAnyHeader()
            .AllowAnyMethod();
             });
        });

But if it is stil not working, you can try to replace default Cors policy with named policy


public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("AllowOrigins", builder =>
            {
                builder.WithOrigins("http://localhost:5500")
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

        .....
            
        }

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

            app.UseRouting();
            app.UseCors("AllowOrigins");
           app.UseAuthorization();

            ....
         }

Upvotes: 1

Related Questions