I am experiencing an issue where my AngularJS CORS request is not reaching the server

Recently, I encountered a problem with my Spring MVC API backend where CORS was correctly configured. However, when attempting to make an Ajax call, Chrome threw the following error:

XMLHttpRequest cannot load 172.20.16.45:8082/cuponza. The request was redirected to '172.20.16.45:8082/cuponza/', which is disallowed for cross-origin requests that require preflight.

Below is the snippet of my JavaScript code:

    $scope.sendRegistrationForm = function(){
        var config = {headers:  {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods' : 'GET,OPTIONS',
        'Access-Control-Allow-Headers' : 'X-Requested-With, Content-Type',
        'Content-Type' : 'text/plain',
        'Accept-Language' : 'en-US'
    }
};
        $http.get("172.20.16.45:8082/cuponza",config).
    success(function(data){
            alert(data);
        }).
        error(function(data,status){
            alert(status);
        })
        }

I attempted running Chrome with the flag --disable-web-security, and it revealed that my server-side CorsFilter was functioning as expected. However, upon normal startup of Chrome, the filter on the server did not engage.

An update: removing the config object with the CORS headers resulted in a new error message:

    XMLHttpRequest cannot load 172.20.16.45:8082/cuponza

. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '
    localhost:8100' is therefore not allowed access

Furthermore, when inspecting the requests made by Chrome, the differences between starting normally and with the --disable-web-security mode were evident:

Starting Chrome normally: OPTIONS /cuponza HTTP/1.1 Host: 172.20.16.45:8082 Connection: keep-alive Access-Control-Request-Method: GET Origin: localhost:8100 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36 Access-Control-Request-Headers: access-control-allow-origin, accept-language, access-control-allow-headers, access-control-allow-methods Accept: / Referer: localhost:8100/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

Starting Chrome in --disable-web-security mode: GET /cuponza HTTP/1.1 Host: 172.20.16.45:8082 Connection: keep-alive Access-Control-Allow-Origin: * Accept-Language: en-US Access-Control-Allow-Headers: X-Requested-With, Content-Type User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36 Access-Control-Allow-Methods: GET,OPTIONS Accept: / Referer: localhost:8100/ Accept-Encoding: gzip,deflate,sdch

Answer №1

There are two important steps you need to take for the solution.

Firstly, in your front end code, make sure to include an empty configuration object like this:

var config = {};

Then, ensure that it is added to the angular call $http.post(url.config);. The reason for this is that without the empty config object, Angular defaults the method type to POST and checks if the content-type is text/plain. Since it's not set by default, sending empty params changes the method to option, triggering different filtering logic.

Secondly, in your web.xml file under filter settings, add the following header: access-control-allow-origin to the allowed headers list as shown below:

<init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,access-control-allow-origin</param-value>
    </init-param>

Once these steps are completed, your Tomcat server will be ready for CORS requests.

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

Utilizing Semantic-UI-React and Webpack to Set the Path for an Image

I am currently developing a ReactJS application using webpack. This basic example is supposed to display an <img> tag with a specified URL in the src attribute. How can I bundle the image resource using webpack and process it with the appropriate l ...

Steps to build a website with working AJAX functionality

Recently, I installed the AJAX-ToolKit in my VS 2005 (c#) and now have access to Ajax controls in my toolbox. However, I am facing issues with creating an AJAX-Enabled template for my website. Can someone please help guide me on how to set up and configur ...

Unexpected halt in execution - VS Code Logpoint intervenes abruptly

Recently, I delved into the world of JavaScript/TypeScript development in VS Code. Intrigued by Eclipse Theia, I decided to explore it further by setting up a backend service. To track its execution, I added a logpoint to my backend service to see when it ...

Retrieving data synchronously from a Promise with Angular

I am looking to display the product history by retrieving the id of the product from the ActivatedRoute.params. In the ngOnInit method, I need to fetch all the historical records of the product and store them in a variable. Afterwards, I want to merge the ...

Looking to retrieve the coordinates of an element following a CSS3 translation using JavaScript?

I came across this issue in two different variations on stackoverflow, but unfortunately the proposed solutions didn't work for me. My problem is that I need to translate an item, but when I try to retrieve its position with obj.style.left or obj.off ...

Setting up Bootstrap 5 with the latest version of Angular, which is Angular

I attempted to install Bootstrap in Angular 13 using the following link: However, after updating to bootstrap v5, the styles are not displaying correctly. Interestingly, it works fine with bootstrap 4.6.1. I followed all the steps in the provided link. I ...

JavaScript: Trouble with statement execution

My code is designed to classify a point as 1 if it's above the line y=x, and -1 if it's below the line y=x. I visually represent this line in a canvas by plotting y=x (although due to invertion on the y-axis, it appears like y=-x). For each point ...

Adjusting the starting point on a 2D canvas with EaselJS translation

When using plain javascript, I was able to change the origin of the canvas to the center by following these steps: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.width = 1024; canvas.heigh ...

Input Error in ASP.NET JavaScript

Within my ASP.NET website, I have implemented an <asp:TextBox /> where the text input is encoded using HttpUtility.HtmlEncode(); Furthermore, the page is equipped with validation controls like <asp:RequiredFieldValidator /> and <asp:CustomV ...

Following an AJAX request, jQuery.each() does not have access to the newly loaded CSS selectors

Note: While I value the opinions of others, I don't believe this issue is a duplicate based on the provided link. I have searched for a solution but have not found one that addresses my specific problem. Objective: Load HTML content to an element u ...

Return to the previous URL after executing window.open in the callback

I need help redirecting the callback URL back to the parent window that initially called window.open. Right now, the callback URL opens inside the child window created by the parent. Here's the scenario: The Parent Window opens a child window for aut ...

Best practices for managing non-PrivateRoutes in React

In my app.js, I have set up a PrivateRoute that requires user login and only grants access if the cookie is set. However, I want to prevent users from accessing /login after they have logged in successfully. To achieve this, I implemented a LoginRoute wi ...

Isotope data-filter not working properly following an Ajax callback

I'm looking for a way to create a filter that can be dynamically updated: I have utilized the isotope javascript library in an external script file: var $container = $('.isotope'); // initialize isotope $container.isotope({ ...

Is there a way for me to determine the proportion of my tests that are covered?

I am eager to determine the coverage of my project through my tests, and I am currently experimenting with the use of jest for this purpose. Here is the content of my jest.config.js: module.exports = { verbose: true, preset: '@vue/cli-plugin-unit ...

Analyze the individuals listed in one column of the table and calculate the total from the adjacent column using JavaScript

I have a table with participant data that I would like to compare. If a participant has multiple result points in the table, I want a script to calculate the sum of all their results. This process should be repeated for each participant listed in the table ...

Having trouble with ng-model in AngularJS and Ionic's date picker functionality?

Having some trouble setting a default value in my ionic date picker, it appears to be getting ignored. The software versions being used are; Ionic "1.3.2" Node v14.15.4 AngularJS v1.8.0 ion-datetime-picker.min.js (version unknown) Here's w ...

What aspects of MongoDB security am I overlooking?

Is it a secure way to connect to Mongo DB by using Node JS, Mongo DB, and Express? Could someone provide an explanation of this code in terms of security? === Many tutorials often only show... var mongoClient = new MongoClient(new Server('localhos ...

Applying styled text to a Node.js chat application

I developed a chat application using node.js which allows users to enter a username and send messages. The messages are displayed in a <ul> format showing "username: message". I was looking for a way to make the username appear bold and in blue color ...

The JSON data structure is not being maintained

I am facing an issue with updating the json object model values using the code below. Even after changing the values, it seems like the model is not getting updated. I tried removing the async code and that worked. Why does the async code not work in this ...

Ensure that the table is updated after every individual character input

I recently posted a question regarding how to refresh an element without refreshing the entire webpage. I've been studying ajax for some time now, but I am struggling to make it work. My goal is to dynamically update a table that primarily displays S ...