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.
- 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"
}
- 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>
Once user selects the menu option "Product Information", another html page is displayed This is coded in productinfo.html
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));
- 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
- When I test the web api in browser directly , it works properly
- 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..
- 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