Page 1 of 2 12 LastLast
Results 1 to 10 of 14

Thread: (CORS) Cross-Origin Resource Sharing requests

  1. #1
    Sencha User luismerino's Avatar
    Join Date
    Oct 2011
    Location
    Berlin
    Posts
    46

    Lightbulb (CORS) Cross-Origin Resource Sharing requests

    Hi all:

    With a growing number of services allowing the use of XMLHttpRequest2 and its advantages, I found if anything annoying that ST2 didn't provide a convenient way of making use of Ext.Ajax and proxy.Ajax to requests data cross domain.

    At first I started using the Ext.Ajax singleton's property Ext.Ajax.useDefaultXhrHeader = false/true, but I hated having to switch its value between calls and besides, using it like this can cause some headaches.

    For this reason, I'm sharing now the cleanest solution I've come up with (not the shortest) to make things a bit easier on this subject.

    Code:
    Ext.define('Ext.data.Cors', {
        
        extend: 'Ext.data.Connection',
        
        alternateClassName: ['Ext.Cors'],
        
        singleton: true,
        
        useDefaultXhrHeader: false,
        
        autoAbort: false
        
    });
    Code:
    Ext.define('Ext.data.proxy.Cors', {
        
        extend: 'Ext.data.proxy.Ajax',
        
        uses: ['Ext.data.Cors'],
        
        alias: 'proxy.cors',
        
        alternateClassName: ['Ext.data.CorsProxy'],
        
        doRequest: function(operation, callback, scope) {
            var writer  = this.getWriter(),
                request = this.buildRequest(operation, callback, scope);
                
            if (operation.allowWrite()) {
                request = writer.write(request);
            }
            
            Ext.apply(request, {
                headers       : this.headers,
                timeout       : this.timeout,
                scope         : this,
                callback      : this.createRequestCallback(request, operation, callback, scope),
                method        : this.getMethod(request),
                disableCaching: false // explicitly set it to false, ServerProxy handles caching
            });
            
            Ext.Cors.request(request);
            
            return request;
        }
    
    
    });
    Note that for the proxy to work, you must override Ext.data.Model like this:

    Code:
    Ext.define('YourNamespace.data.Model', {
         override: 'Ext.data.Model',
         requires: ['Ext.data.proxy.Cors']
    });
    Since I don't advice you to mess around with ST2 source's at all (updates will break your code if replaced).

    I'm not sure if somebody proposed some other solution for CORS requests about the forum, but anyhoo.

    Enjoy

  2. #2
    Sencha Premium User mitchellsimoens's Avatar
    Join Date
    Mar 2007
    Location
    Gainesville, FL
    Posts
    40,448

    Default

    This is excellant. Haven't tested it myself but it looks like it is good.
    Mitchell Simoens @LikelyMitch

    Check out my GitHub:
    https://github.com/mitchellsimoens

    Posts are my own, not any current, past or future employer's.

  3. #3

    Default Update for PR4

    Great job Luis, works like a charm.

    ST PR4 rewrote the doRequest method a little bit, so I had to grab the new version from the sencha-*.js file and modify to make it go again. Code below.

    PHP Code:
    doRequest: function(operationcallbackscope) {
            var 
    writer  this.getWriter(),
                
    request this.buildRequest(operation);

            
    request.setConfig({
                
    headers       this.getHeaders(),
                
    timeout       this.getTimeout(),
                
    method        this.getMethod(request),
                
    callback      this.createRequestCallback(requestoperationcallbackscope),
                
    scope         this,
                
    disableCachingfalse // explicitly set it to false, ServerProxy handles caching
            
    });

            
    // We now always have the writer prepare the request
            
    request writer.write(request);
                    
    Ext.Cors.request(request.getCurrentConfig());

            return 
    request;
        } 

  4. #4

    Default

    In ST 2.0 I had to put the settings inside the config block to get it to work:

    Code:
    Ext.define('App.data.CrossOriginConnection', {
    	extend: 'Ext.data.Connection',
    	singleton: true,
    	config: {
    		autoAbort : false,
    		useDefaultXhrHeader: false
    	}
    });
    Would be nice if ST would provide CORS aware proxies in the future.

  5. #5
    Sencha User
    Join Date
    May 2010
    Posts
    32

    Default

    I'm still new to Sencha Touch.

    Where exactly do I place this code? In what folder? and under what file name?

  6. #6
    Sencha Premium Member
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    124

    Default

    Hi,

    I'm too relatively new to this topic and am totally confused how to implement CORS in ST2. Is there by now a convenient way to enable it?

    Also, just like bnerd I'm not sure on how to use this example with ST2.0.1.

    mitchellsimoens noted here that ST supports CORS now. But I do not really now how.

    Anyone willing to enlighten me?

    Thanks a tousand times!

  7. #7
    Sencha User luismerino's Avatar
    Join Date
    Oct 2011
    Location
    Berlin
    Posts
    46

    Default

    Hi, I've been quite a while away from ST2, but the basic paradigm is (or it was) that the Ajax proxy won't use the CORS config unless X-Requested-With is not included in the headers, and for that you need to prevent it explicitly.

    When dealing with cross domain requests, most server-side solutions or frameworks would filter requests with such header as "ajax" and you wouldn't want that filter to be applied.

    Hope it helps.

  8. #8
    Sencha Premium Member
    Join Date
    Mar 2012
    Location
    Sydney, Australua
    Posts
    73

    Default Example please

    Hi,

    I am also confused by this.

    Can someone please post a working example app that uses CORS to get data from a web service, and plug it into a data store.

    Thanks,
    Adam.

  9. #9
    Sencha Premium User mitchellsimoens's Avatar
    Join Date
    Mar 2007
    Location
    Gainesville, FL
    Posts
    40,448

    Default

    Simple to do:

    Store:

    Code:
    new Ext.data.Store({
        autoLoad : true,
        fields   : ['test'],
        proxy    : {
            type  : 'ajax',
            url   : 'http://test/data/php.php'
        },
        listeners : {
            load : function(store, recs) {
                console.log(recs);
            }
        }
    });
    php.php:

    PHP Code:
    <?php

    //CORS
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: X-Requested-With');

    //JSON
    header('Content-Type: application/json');

    $array = array(
        array(
            
    'test' => 'one'
        
    ),
        array(
            
    'test' => 'two'
        
    )
    );

    echo 
    json_encode($array);

    ?>
    And now it will work!
    Mitchell Simoens @LikelyMitch

    Check out my GitHub:
    https://github.com/mitchellsimoens

    Posts are my own, not any current, past or future employer's.

  10. #10
    Sencha Premium Member
    Join Date
    Mar 2012
    Location
    Sydney, Australua
    Posts
    73

    Default

    We had these changes made to the server and finally it worked!

    # add these lines after the htdocs directory section
    <Directory "/usr/local/apache2/htdocs/ws">
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET,POST"
    Header set Access-Control-Allow-Headers "x-prototype-version,x-requested-with"
    </Directory>


Page 1 of 2 12 LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •