Solving CORS policy errors in Dot Net Core Web API using Javascript

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.

  1. 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"
}
  1. 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>
  1. When selecting "Product Information" from the menu, a separate HTML page named productinfo.html is displayed.

  2. 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));
  1. 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:

  1. Testing the Web API directly in the browser works fine.
  2. 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.
  3. 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

Answer №1

If you're encountering a bug in Cors syntax, here is the correct way to implement default policy:

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

If the issue persists, consider trying to replace the default Cors policy with a 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();

            ....
         }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for downloading MP3 files using ASP.NET MVC 5 and Entity Framework

I have successfully completed the uploading process - I uploaded the MP3 files to my SQL Server. However, I am in need of assistance with downloading the files. Below is the code I used to upload the MP3 file: public ActionResult Create([Bind(Include = "I ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Refine radio button list based on input typed in text box

How can I filter my checkbox list based on letters typed into a textbox? The data for my checkbox list comes from a database. I attempted to do this using JavaScript, but it's not working. Is there a better way to achieve this functionality? <asp: ...

Executing Multiple setTimeout jQuery in a Class: A Comprehensive Guide

Is there a way to hide elements with the class .content and the attribute .data-time using the setTimeout() function in jQuery? Here is the HTML code: <div class="content first" data-time="200"> </div> <div class="content second" data-time ...

Refresh your textarea content using the replace method in jQuery

My goal is to extract and manipulate specific values within a user-entered code using jQuery. The code includes custom tags called setting, which I want to extract and display in input fields for easy editing. I have successfully retrieved and displayed th ...

Div adjusts its height to match another div's, regardless of the latter's size

I'm currently working on a website where I have a list of news displayed in divs. Each div contains two inner divs: an image on the left and the title, date, and the first 30 words of the news on the right. I am looking to make the image div adjust it ...

Is it possible to access an external JavaScript file in the main.js by importing it?

In this scenario, I have defined an array of countries in an external Javascript file. const countries = [ "Australia", "Brazil", "China", "Denmark", "Egypt", "France", "Germany", "Hungary", "Italy", "Japan", ...

Issue with Angular ng-model not functioning as expected within ng-repeat block

Encountering an issue when trying to bind Json data into ng-model within ng-repeat. html : <div ng-controller="Ctrl"> <div> <table> <th> <td>add</td> <td>ed ...

The script generated by document.write is failing to function as expected

A completed JQuery script has been created to enable the movement of a 360° object (picture) based on mouse actions. The code is functional: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> ...

Ways to output HTML from a function

I'm struggling to get my HTML function to work properly, even though it seems like a simple task. For some reason, the content isn't displaying when I return it, but things work fine when using console.log. Could someone please assist me with th ...

Conceal Firefox Navigation Bar with Selenium in C#

Automating tasks with Selenium has been an interesting journey. Check out my code snippet: FirefoxOptions options = new FirefoxOptions(); options.AddArguments("--disable-infobars"); FirefoxDriver driver = new FirefoxDriver(firefoxDriverService, o ...

What is the method for obtaining receipt numbers in sequential order, such as the format AB0810001?

Is AB the receipt code that should remain constant followed by the current date (08) and 10001 as the receipt number? ...

When onSucess is called within a Vue view, the metadata parameter returns undefined, whereas it works properly inside a

In my Vue component for Plaid Link, there is a function/action in my Vuex store called onSuccess. This function is supposed to call my backend API to exchange the public token for an access token and send some data about the link to the backend. However, I ...

Is it possible to convert a .gif file into a jpeg image format for mobile display on my Gatsby website?

I'm looking to convert a .gif file into a mobile.png image for my Gatsby site, but I'm struggling to find the right resources. Does anyone have suggestions on how I can achieve this? Here is the frame: https://i.sstatic.net/IjYv4.png ...

Unlocking secure content with Ajax

Trying to access a webservice or webpage solely through ajax, as it is the only allowed method for some reason. The webservice is secured with corporate SSO. When requesting webpage X for the first time, you are redirected to login page Y, outside of the a ...

The function putImageData does not have the capability to render images on the canvas

After breaking down the tileset The tiles still refuse to appear on the <canvas>, although I can see that they are stored in the tileData[] array because it outputs ImageData in the console.log(tileData[1]). $(document).ready(function () { var til ...

Is it possible to manipulate a modal within a controller by utilizing a certain attribute in HTML, based on specific conditions (without relying on any bootstrap services), using AngularJS?

Within my application, I have a modal that is triggered by clicking on a button (ng-click) based on certain conditions. Here is the HTML code: <button type="button" class="btn btn-outlined" ng-click="vm.change()" data-modal-target="#add-save-all-alert ...

Issue on Heroku with Discord.js displaying a "Service Unavailable" message

Encountered a strange error while trying to launch my discord bot on heroku. Previously, I implemented a command handler for the bot to organize commands in separate files but faced multiple code errors. With the help of a member from this community, all e ...

The Wikipedia API is unable to be loaded using the XMLHttpRequest

I have encountered this error before on this platform, and although I managed to fix it, I am seeking a more in-depth explanation of the solution. For a project where I am learning, I decided to create a Wikipedia Viewer application. The first step was to ...

Obtain a collection of Objects containing key/value pairs by utilizing a webmethod or pagemethod

Seeking assistance on retrieving values from an Array of objects based on a key. Similar to this JavaScript: PageMethods.GetProducts(function(results) { var productName = results[0].name; }); However, in the code behind, I am encountering an issue wh ...