Ember now offering support for XDomainRequest(xdr) to manage CORS restrictions

I am currently utilizing ember 1.5 with grunt-cli and I would like to make an AJAX call for CORS support using dataType: "JSON".

Ember.$.ajax({
    type: "GET",
    url: App.serverURL + 'logVisit', // callback for jsonP
    data : {
        'fp': App.fp
    },
    dataType : "JSON",
    success: function(response) {
        console.log('DEBUG: visitor has been registered');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("DEBUG jqXHR.responseText : ",jqXHR.responseText);
        var response = jqXHR.responseText;

        console.log('Failure!');
        if(jqXHR.status&&jqXHR.status==400){
            // alert(jqXHR.responseText);
            var response = $.parseJSON(jqXHR.responseText);

            if (response) {
                console.log(response.error);
            } else {
                // This would mean an invalid response from the server - maybe the site went down or whatever...
                console.log("DEBUG: Inside jqXHR.status : Something went wrong");
            }
        } else {
            console.log("DEBUG: Something went wrong");
        }
    }
});

In IE10/11, everything is working fine. However, in IE8/9, it doesn't work properly as it requires XDR object, leading to the following console output:

LOG: DEBUG jqXHR.responseText: undefined
LOG: Failure! 
LOG: DEBUG: Something went wrong

Any suggestions or workarounds?

My Request Header:

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36

Response headers in browsers other than IE 8/9

Access-Control-Allow-Origin:*
Content-Type:application/json
Date:Wed, 25 Mar 2015 16:01:56 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked

Answer №1

Thanks to @Isowen's reply, I was able to find the solution I needed.

To enable XDR for IE8/9, I inserted the following code snippet just before

window.App = Ember.Application.create({});

Ember.$.ajaxTransport( function( options, originalOptions, jqXHR ) {
  var xdr;

  return {
    send: function( _, completeCallback ) {
      xdr = new XDomainRequest();
      xdr.onload = function() {
        if (xdr.contentType.match(/\/json/)) {
          options.dataTypes.push("json");
        }

        completeCallback(200, 'success', { text: xdr.responseText } );
      };
      xdr.onerror = xdr.ontimeout = function() {
        completeCallback(400, 'failed', { text: xdr.responseText } );
      }

      xdr.open(options.type, options.url);
      xdr.send(options.data);
    },
    abort: function() {
      if(xdr) {
        xdr.abort();
      }
    }
  };
});

Additionally, based on @Isowen's advice, make sure to include the following while making ajax requests:

Ember.$.ajax({
    type: "GET",
    url: App.serverURL + 'logVisit',
    data : {
        'fp': App.fp
    },
    dataType : "JSON",
    xhrFields: {withCredentials: true},
    ....
});

For those using REST adapters for request handling, you can utilize the below code:

App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: App.host,
    namespace : App.namespace,
    ajax: function(url, method, hash) {
        hash = hash || {};
        hash.crossDomain = true;
        hash.xhrFields = {
            withCredentials: true      
        };
        console.log('DEBUG: inside RESTAdapter ajax call');
        return this._super(url, method, hash);
    }
});

When working with backend technologies like Spring - Java, consider including the following CORS filter:

@Component("corsFilter")
public class CORSResponseFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

            response.addHeader("Access-Control-Allow-Origin", "http://YOUR-LINK");
            response.addHeader("Access-Control-Allow-Credentials", "true");
            if (request.getHeader("Access-Control-Request-Method") != null
                && "OPTIONS".equals(request.getMethod())) {
            
            // Additional CORS configurations for pre-flight requests
            response.addHeader("Access-Control-Allow-Methods",
                    "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers",
                    "X-Requested-With,Origin,Content-Type, Accept");
        }
        filterChain.doFilter(request, response);
    }
}

A big thank you goes out to @Isowen for the invaluable assistance provided.

Answer №2

Make sure to include the xhrFields.withCredentials parameter set to true.(Not always necessary for CORS requests, and has limited support in IE10).

Verify that your server is sending the Access-Control-Allow-Origin header with a value matching your request origin.

The issue could be related to the server-side CORS implementation. You can test a modified version of your code on jsfiddle running against httpbin.org to verify it works correctly across different browsers: http://jsfiddle.net/n94w774n/.

EDIT:

If both the Origin and Host are localhost (but with different ports), you may need to adjust Security Zone settings for localhost. Check out this link for more information: Access denied in IE 10 and 11 when ajax target is localhost

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

The initial value set for the innerHTML property of a div element

I have a requirement in my application where I need to confirm if the container div is empty before adding specific text elements to it. The innerHTML of this div is frequently created and removed within the app, so it's crucial to validate its emptin ...

Picked (chosen-js): Steps to deselect options using a variety of selectors

I am currently using the Chosen library on Vue and Webpack for my project. I have a scenario where I need to cancel a selection when multiple options are selected, but I am struggling to achieve this. Can anyone guide me on how to cancel a selected optio ...

Encountering a glitch when utilizing framer-motion's Animated Presence feature

I am working on a React slider where new data replaces old data whenever the user clicks on the Next or Previous button. To enhance the slider with beautiful animations, I decided to use framer motion. The animations are almost perfect, but for some reason ...

Form with missing input fields submits nothing to the server

I created a Node project with a single view page for users to access information. When I use an HTML form to send data, the content is empty. I have verified multiple times using Postman that the information is being saved successfully when sent with the P ...

Utilizing React to Style Background Positions

I've been struggling to position a block of rendered jsx on the right side of the first block for hours now. Despite trying various options like marginTop, marginLeft, and even backgroundPosition based on my research, I still haven't been success ...

Retrieving Database Data using Ajax Cascading DropDownMenus

This project marks my first experience with Ajax and C#.NET. As a newcomer using .NET 4.0, I have successfully integrated a cascading dropdown feature that stores data in the database upon submission. However, I have encountered a roadblock when it comes t ...

Create a Java program that causes an ImageView to shake

I want to create the effect of shaking an ImageView when it is clicked using Java programming only. I have searched for solutions to this issue, but most of them involve XML code. Can someone provide a solution that involves only Java? ...

Leverage closures within Underscore.js templates for enhanced functionality

Is there any benefit to utilizing a closure in an underscore template for purposes such as keeping track of counters? Here's a simple example: <% (function( models ){ var length = models.length-1, section = ""; _.each( models, functi ...

In TypeScript, the function is failing to retrieve the complete array value

I'm facing an issue with a program that is supposed to piece together all the letters, but it's not functioning correctly. I've tried using the debugger, but it doesn't display any errors. Here's the code snippet: var phrase = [ &a ...

Obtain the rows of selected cells from a nested context menu of JMenuItems in Java Swing

Issue: When making a selection of multiple cells in my Jtable and then right-clicking, I am unable to obtain the selected cell references from the nested or sub-menu options. Below are snippets of my code: private JMenuItem menuItem1; private JMenuItem m ...

Convert an array of JSON objects into a single JSONObject array

The example shows a JSONArray structured like this: [["title","details"],["abc","xyz"],["abc2","xyz2"]] I am looking for a way to convert it into an Array of JSONObject using Java or JavaScript, with the format shown below: [ { 'title': abc, ...

Executing queries in Java that search for MongoDB fields beginning with specific characters

Is there a way to perform a "Like" query, but only scan results from the beginning? In other words, I want the query to be based on "starts with". List<Account> findByUserInfo_FirstNameRegexAndUserInfo_LastNameRegexAndEmails_EmailIDRegex(String firs ...

Inkwell shifts bespoke quality

I am currently utilizing Quill (v.2.0.0) with quill-better-table (v.1.2.10) within my Angular 13 project. I am attempting to incorporate a custom attribute to the table tag, as shown below: <table class="quill-better-table" custom-attribute=& ...

managing various object types in a versatile manner

I've encountered an issue with a function that checks the type of the argument being passed: public void myFunc(Object myObj){ if(myObj instanceof Student){ Student p = (Student) myObj; }else{ Teacher p = (Teacher) myObj; ...

How do I make the YouTube Grid Gallery player show up in a pop-up window?

I have been experimenting with the following code: <head> <script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script> <script type="text/javascript"> function loadVideo(playerUrl, ...

Lagging speeds in client-side template rendering using Rivets.js

I have a function that renders an array of around 1000 objects, but the html bindings are causing significant performance issues. It currently takes about 5 seconds to complete rivets.bind(). Does anyone have any recommendations for improving performance? ...

Is there a way to automatically change the display of an element once the user has closed the menu?

How can I ensure that the display of an element remains unchanged when a user opens and closes my website menu using JavaScript? ...

The Ajax request seems to be malfunctioning

I've been attempting to send a value to a controller method (using CodeIgniter) via AJAX with jQuery. I've set up the AJAX call within a click event, and while the event works fine, the AJAX request is not being made. Any guidance on this issue w ...

Refresh the array using Composition API

Currently, I am working on a project that utilizes Vue along with Pinia store. export default { setup() { let rows: Row[] = store.history.rows; } } Everything is functioning properly at the moment, but there is a specific scenario where I need to ...

When a change is made in the parent component, the local state of the child component in ReactJS is automatically updated

I'm currently facing a challenge while implementing a custom dropdown filter for a table in react. Each column has a set of dropdown values with an Apply button. To handle this, I've created a child component that takes the dropdown values and s ...