Enable CORS for AJAX requests with RESTful web services in Google Chrome

My web-based project is fully written in jQuery and JavaScript. On the client side, I am calling RESTful webservices via AJAX like this:

 $.ajax({
    type: 'GET',
    timeout: 1000000000,
    headers: { 'Access-Control-Allow-Origin': '*' },
    url: serverName + '/getAlerts/',
    data: {}, 
    dataType: "text", 
    success: function (data) {
        $scope.alerts = JSON.parse(data);
        $scope.$apply();
    },
    error: function (data) {
        alert(errServiceCall); 
    }
});

In the server side, the RESTful webservices are created in Spring. An example function looks like this:

@RequestMapping(value = "/services/getAlerts", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
@ResponseBody
public String getAlerts(HttpServletRequest request) throws JSONException, IOException, SQLException {
    return "hello it's me";
}

However, when I try to call that function on Chrome, I encounter the following error:

(index):374 Refused to connect to '' because it violates the following Content Security Policy directive: "connect-src 'self'".

If I manually enter the RESTful URL () in the Chrome address bar, it returns the result successfully.

I believe this issue is related to CORS (Cross-Origin Resource Sharing), so I included the code:

headers: { 'Access-Control-Allow-Origin': '*' },

In my AJAX code block. However, this did not solve the problem.

To address the CORS problem, I attempted to add the @CrossOrigin parameter above the function on the server side like this:

@CrossOrigin
@RequestMapping(value = "/services/getAlerts", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
@ResponseBody
public String getAlerts(HttpServletRequest request) throws JSONException, IOException, SQLException {
    return "hello it's me";
}

But in doing so, I encountered the following error at compile time (Java version 1.6 + spring version 4.3.12):

annotation org.springframework.web.bind.annotation.CrossOrigin is missing < clinit>

How can I effectively resolve this CORS issue?

P.S: The process works perfectly in Internet Explorer when I enable CORS from Internet Options -> Security -> Custom Level -> Miscellaneous -> Access data sources across domains.

Answer №1

In order to solve the CORS problem, I made modifications to the virtual host configuration file on a Unix WebSphere Application Server hosting RESTful web services built using the Spring framework. By adding the following code snippet, I was able to successfully call AJAX functions on the client-side without needing any browser configurations.

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token, x-csrftoken"
Header always set Access-Control-Allow-Credentials "true"

If you are interested in delving deeper into this configuration, you can refer to this page. It provides valuable insights and guidance.

Answer №2

Have you included

$.ajax({
    ....
    xhrFields: {withCredentials: true},
    ....
}

inside the ajax function?

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

Retrieve a comprehensive inventory of all routes within a Vue project and automatically create a sitemap for the website - Vue Project

Imagine I've set up a route like this: import Vue from "vue"; import Router from " vue-router"; import BookRoutes from "./routes/book"; Vue.use(Router) const router = new Router({ routes:[ { path ...

Loading website with continuous HTML5 video playback

I'm currently working on a website that features a large section with a video background set to loop. To enhance the user experience, we decided to include a preloading image while the site loads its resources. Our current setup involves using jQuery ...

Guide to achieving a powerful click similar to a mouse

I've been struggling to get an audio file to play automatically for the past three days, but so far I haven't had any luck. The solutions I've tried didn't work in my browser, even though they worked on CodePen. Can anyone help me make ...

Surprise mistake: Jade's error with the length

What can I do to address this problem? The jade file in question is as follows: extends layout block content h1. User List ul each user, i in userlist li a(href="mailto:#{user.email}")= user.username U ...

Tips on choosing and retrieving the value of filled text area fields using jQuery

I am struggling with selecting non-empty textareas and retrieving their values using jQuery. Here is a snippet of my code: <div class="item"> <textarea class="col-sm-10 comment">TextArea1</textarea> </div> <d ...

Dealing with duplicate entries in a dropdown menu when receiving a JavaScript AJAX response

I am attempting to display multiple selected values in a dropdown list that are coming from a database. The contents of my dropdown list are dependent on another dropdown list. Here is the JS code I am using: var cityName = <?= json_encode($cityName); ...

Ways to duplicate the content of a div to the clipboard without the use of flash

Simple question! I have a div identified as #toCopy, along with a button identified as #copy. Can you suggest the most efficient method to copy the content of #toCopy to the clipboard upon clicking #copy? ...

"Eliminating Redundant JS and CSS Files in Magento to Improve

While analyzing the performance of a website, I noticed that GTmetrix found some CSS & JS files being loaded from different locations but containing the same file. An example: <action method="addItem" module="ves_blockbuilder" ifconfig="ves_blockbuilde ...

Ensure all asynchronous Ajax requests have completed before considering the page fully loaded

Many websites, such as YouTube, load the majority of their content after the DOM is ready using JavaScript. How can I ensure that all of these requests have been completed before injecting my code? window.onload = function() {}; The above code snippet do ...

Navigating the landscape of asynchronous asset loading can present challenges. Attempting to access assets immediately may result in receiving

I have encountered an issue while trying to load my assets into an array using a function called LoadJSON(). This function utilizes THREE.ObjectLoader() to load JSON files. The problem arises when I attempt to access the members of the array immediately af ...

Access the elements within arrays without using the square brackets

I am trying to access data from a list, but I am having trouble using square brackets []. The getTalonPaie function calls the get method from the HttpClient service and returns an observable with multiple values. However, when I try to store these values i ...

"Receiving a 404 error when sending a POST request, but getting

When attempting to send a POST request, I encountered a 404 error response from the server. Strangely, when sending a GET request, I received a 200 response. I have experimented with different methods: $.ajax({ type:"POST", url: "script.php", ...

Issue with the iteration process while utilizing Async.waterfall in a for-loop

This snippet may seem simple, but it represents a real issue in my current code base. When attempting to log the index of a for-loop within an async.waterfall function, I am encountering a peculiar situation where the index value is 2 instead of expected ...

In PHP, it is essential to always complete the necessary information in form validation

I've been working on implementing JavaScript form validation, but I seem to be having trouble with testing for empty fields in the form. Whenever I submit a fully filled out form, it keeps asking me to fill in the blank fields. Here is the code I hav ...

Launching a hyperlink in a fresh tab

When using Selenium, I encountered an issue with opening a link in a new window. After some research, I came across the following two methods: 1) Actions act = new Actions(driver); act.contextClick(we).perform(); myWait(1000); // allow the menu to come u ...

What steps can I take to stop the textfield from automatically changing the ID "myid" to "myid-tokenfield" when using Tokenfield for Bootstrap?

While utilizing Tokenfield for Bootstrap, I have encountered an issue where the id of my textfield gets modified from myid to myid-tokenfield. In order to properly interact with the search engine I am using, this textfield must maintain a specific id. The ...

Behavior of routing not functioning as anticipated

In my app-routing.module.ts file, I have defined the following routes variable: const routes: Routes = [ { path: '', redirectTo: '/users', pathMatch: 'full' }, { path: 'users', component: UsersComponent }, ...

How to make a JQuery list item unselectable when appending it

I encountered a strange issue while using jQuery to append items to a list. <ul id="idNicheItems" class="clScrollItems ui-widget-content ui-corner-all"> <li id="NicheItem_1"> Item 1</li> <li id="NicheItem_2"> Item 2</li& ...

Encountering a CSS issue during the edit process with PHP and JavaScript

I'm encountering an issue when clicking on the edit button, as my data fetched from the DB should be displayed inside a text field. However, I'm facing a CSS-related error: Uncaught TypeError: Cannot read property 'style' of null Belo ...

What is the best way to locate the overridden method in Android Studio for Activity.runOnUiThread()?

After reviewing the source code of Activity.java, I noticed the @Override annotation. But my question is, what specific method does this override? Additionally, is there a shortcut in Android Studio to navigate directly to the parent interfaces or classe ...