In my development environment, I am utilizing Visual Studio Code with liveserver for HTML and JavaScript, while also using Visual Studio 2019 for Dot Net Core Web API. I have set up the site in IIS on Windows 10 locally for the web API.
- My login functionality is implemented on a page called login.html
Within the login page, there is a JavaScript function that triggers upon clicking the login button:
function fnlogin() {
window.location.href = "http://localhost:5500/productmenu.html"
}
- After successfully logging in, users are directed to a menu page coded in productmenu.html:
<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>
When selecting "Product Information" from the menu, a separate HTML page named productinfo.html is displayed.
Upon entering a product code and initiating a search, a Dot Net Core web API is utilized to fetch data and present it on the productinfo.html page through the fetch API.
The API call within the JavaScript looks like this:
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 configuration for the Dot Net Core Web API can be found in the startup.cs file:
method: configureServices
services.AddDefaultPolicy(
options.AddDefaultPolicy (
builder =>
{
builder.WithOrigins("http://127.0.0.1:5500)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
})
)};
The configure method includes:
app.UseRouting();
app.UseCors();
app.UseAuthorization():
The Web API is hosted on an IIS site with port 8082.
The issue arises when:
- Testing the Web API directly in the browser works fine.
- Running the productmenu.html in live server opens a new browser window, displaying the menu correctly. Despite this, accessing the "Product Information" page and making a search request results in a CORS error in Chrome dev tools.
- Attempting the same steps as before but starting from login.html in VS code/live server leads to a CORS error during the search action, specifically stating: "Access to fetch...' has been blocked by CORS policy."
Checking the Network tab in Chrome dev tools shows the following Request headers:
Accept: */*
Host: localhost:8082
Origin: http://localhost:5500
Sec-Fetch-Dest: Empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site : same-site