Varois
Varois

Reputation: 131

Ext.data.Connection.override request

I am trying to intercept all requests, before send, from an Extjs App, POST and GET and then manipulate the URL and add a new Header, Authorization: Bearer XYZ123.

I've this code:

Ext.data.Connection.override({

    request: function (options) {
        var me = this;

        this.cors = true;
        this.useDefaultHeader = false;
        this.useDefaultXhrHeader = false;

        options.headers = { "Authorization": "Bearer VAROIS1iOiJKV1QiLCJh" };

        var separator = options.url.indexOf('/') == 0 ? "" : "/";
        options.url = UrlAPIPrefix + separator + options.url;

        return me.callOverridden(arguments);
    }
});

But when i try to use it, the Header Authorization is not sent in both cases, GET and POST. Parameters are not sent when using POST. I am able to see params if debugging the code into Extjs files, but can't see it on chrome Request Headers, see image.

enter image description here

If any one knows how to do it, in one place, i will be glad if you can help me.

Upvotes: 0

Views: 1187

Answers (2)

Benjamin E.
Benjamin E.

Reputation: 5162

That's because Ext.Ajax - the singleton of Ext.data.Connection - is used for most requests in the framework and overriding the latter does not affect the former. This overriding behavior was changed in extjs 5 and is intended by Sencha.

Use what you need of this instead:

Ext.Ajax.setWithCredentials(true);
Ext.Ajax.on({
    beforerequest: function(conn, options) {
        options.headers = options.headers || {};
        options.headers['Authorization'] = 'Bearer VAROIS1iOiJKV1QiLCJh';
    },
    requestexception: function(conn, response, options) {
        Ext.Error.raise('...');
    }
});

And don't hardcode the token into your javascript!!!

Upvotes: 3

JChap
JChap

Reputation: 1441

Instead of overriding the class, i created a bootstrap class to set up the ajax interceptor. Called Bootstrap.init() in Application.launch() method.

Ext.define('MyApp.Bootstrap', {

    singleton : true,

    init: function() {
        Ext.Ajax.on({
            beforerequest: function(conn, opts){
                if(opts.url && Ext.String.startsWith(opts.url, '/')) {
                    return;
                }
                if(opts.url && !Ext.String.startsWith(opts.url, MyApp.Config.SERVER_CONTEXT)) {
                    opts.url = MyApp.Config.SERVER_CONTEXT + opts.url;
                }
                var clientId = MyApp.getApplication().clientId;
                opts.headers = Ext.apply({'X-Client-Id': clientId}, opts.headers);
                Ext.log('Sending Request to : ', opts.url);
            }
        });
    }
});

Upvotes: 1

Related Questions