Docker: CORS policy is blocking access to XMLHttpRequest

After creating an ASP.NET Web Application (.NET Framework) project in Visual Studio 2022 and adding a web service to it, everything seemed to work fine when testing the web service call on Local IIS. However, things took a different turn when I tried running the projects in a container (Windows containers). What could be causing this issue? The error message that pops up is as follows: Access to XMLHttpRequest at 'http://localhost:5002/WebService.asmx/HelloWorld' from origin 'http://172.17.78.68' 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. Below is a snippet of my docker-compose.yml file:

version: '3.4'

services:

  saview:
    image: ${DOCKER_REGISTRY-}saview
    build:
      context: .\SAview
      dockerfile: Dockerfile
    ports:
       - 5001:80
    links:
       - saviewweb
    depends_on:
       - "saviewweb"
    networks:
       - mynetwork

  saviewweb:
    image: ${DOCKER_REGISTRY-}saviewweb
    build:
      context: .\SaviewWeb
      dockerfile: Dockerfile
    ports:
       - 5002:80
    networks:
       - mynetwork

networks:
     mynetwork: 
       driver: nat
       

This is how I am currently making a request using JavaScript:

function Web(arg, url ) {  
    var result;
    
    $.ajax(
        {
            type: 'POST', url: url, data: JSON.stringify(arg),
            dataType: 'json', 
            contentType: "application/json; charset=utf-8", async: false, success: function (res) {
                result = res;
            }
            , error: function (a1, a2, a3) {
                result =
                {
                    d: "_Error_" + a1 + " " + a2 + " " + a3
                };
            }  //-
        });
    if (result.d == null)
        return null;
    if (result.d.indexOf != undefined && result.d.indexOf("_Error_") !== -1) {

        alert(result.d);
        return null;
    }
    return result;
}



Web({}, "http://localhost:5002/WebService.asmx/HelloWorld" );

Answer №1

The issue of CORS arises when an attempt is made to request a domain that differs from the one where JavaScript is executed, such as http://localhost:3000 and http://example.com. The solution lies in addressing it at the server/API level rather than on the front-end.

If the domains are shared, everything should function smoothly.

For further details, please consult the following documentation which covers all necessary information: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

As outlined in the documentation, adding something similar to the code snippet below to your Program.cs file should resolve the issue:

builder.Services.AddCors(options =>
{
    options.AddPolicy(
        name: "cors-policy",
        policy  =>
            {
                policy.WithOrigins(
                    "http://172.17.78.68:<port>",
                    "http://localhost:5002"
                );
            }
    );
});
...
app.UseCors("cors-policy");

In the WithOrigins section, be sure to specify all the "front-ends" that you want to grant access to your API.

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

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

Building a Mongoose Schema with an Array of Object IDs: A Step-by-Step Guide

I created a user schema using mongoose: var userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true}, password: { type: String, required: true}, name: { first: { type: String, required: true, trim ...

Is it possible for AngularJS components to alter their enclosing element?

I see Angular components as element directives. Take a component named hero, for example, I can include it in the parent template like so: <hero myparam="something"></hero> What I envision is using the hero element as a container managed by t ...

What is the best way to locate all mesh faces that are being lit up by a SpotLight

I am working with a THREE.Mesh that consists of a THREE.BufferGeometry containing "position" and "normal" THREE.BufferAttributes. This mesh is being lit by a THREE.SpotLight (which is a cone-shaped light source). Is there a method to ...

What is the best way to deactivate a hyperlink on a widget sourced from a different website?

Is there a way to remove the link from the widget I embedded on my website without access to other editing tools besides the HTML code provided? For instance, we have a Trustpilot widget at the bottom of our page that directs users to Trustpilot's web ...

How to send a contact form in Wordpress with multiple attachments via email without using any plugins

The main objective is to enable users to submit their own content for new articles (including text and files) to the administrator's email. A form has been created for this purpose: <form class="form form-send" enctype="multipart/fo ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Looking for assistance with a simple Javascript program

My program needs to have a for loop and utilize existing input functions (name and number). Additionally, I need to calculate totals. Users should be able to CANCEL and proceed to doc.write where they can enter their name and number. Furthermore, users s ...

Are routes in Next.js easy for search engines to crawl?

Currently, I am developing a movie application using NextJS to enhance my skills. The homepage features each movie's title and a brief description. When a user clicks on a movie, they are taken to a dedicated page that showcases more details about the ...

When using JSON.stringify, the output is null. However, when using document.write, the data

I am currently working on a plugin for crawljax that involves executing some JavaScript code, similar to the following: String result = browser.executeJavaScript(script).toString(); The script code is as follows: function getElementPosition(id) { var el ...

Utilizing AngularJS ng-messages feature across various languages

Utilizing ng-messages to show error messages for form validation in my application. I have a multi-language app, how can I implement ng-messages to support multiple languages? HTML Form <div class="messages" ng-messages="myForm.email.$error"> & ...

Apply CSS styling to the shadow root

In my preact project, I am creating a Shadow DOM and injecting a style element into the Shadow root using the following code: import style from "./layout/main.css"; loader(window, defaultConfig, window.document.currentScript, (el, config) => ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

Changing $scope within an AngularJS service

I am currently working on an application that utilizes the Gmaps API for geolocalization. One of the challenges I faced was adding new markers based on user events. To address this, I created a service that listens to map events and adds markers when click ...

Explore innovative ways to display mathematical equations dynamically on the browser using NextJS version 13.3.0 or consider alternative solutions for showcasing math content with

I'm currently working on developing a web application that allows users to input LaTeX expressions, which are then dynamically displayed in another div or updated within the same input field. After some experimentation with Mathquill and NextJS v13.3 ...

Need a tool for validating forms?

I am currently facing some confusion with the UI Validation plugin that we are using. Within our application, we employ Spring MVC, Jquery & Bootstrap. As we delve into UI development, we have encountered uncertainty in selecting an appropriate Validation ...

Updating to a newer version of jQuery causes issues with pop-out submenus

Looking for a way to create a menu with pop-out submenus? Here's an example using jQuery: <script type="text/javascript"> $(document).ready(function() { var hoverAttributes = { speed: 10, delay: 1 ...

Navigating the loop in Vue using JavaScript

I'm facing an issue where I need to send data at once, but whenever I try sending it in a loop, I end up getting 500 duplicate id status errors. I have a hunch that if I click on something in JavaScript, the data might be sent all at once. assignment ...

The function is trying to access a property that has not been defined, resulting in

Here is a sample code that illustrates the concept I'm working on. Click here to run this code. An error occurred: "Cannot read property 'myValue' of undefined" class Foo { myValue = 'test123'; boo: Boo; constructor(b ...

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...