Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass custom HTTP headers to RESTful requests

I am trying to integrate Backbone in Yii and therefore I need REST. So I installed a Yii extension, restfullyii, which makes use of a username and password that need to be passed to requests. The problem is that I have no idea how to do this with Backbone.

Example of wanted request:

List
curl -i -H "Accept: application/json" -H "X_REST_USERNAME: admin@restuser" -H "X_REST_PASSWORD: admin@Access" http://yii-tester.local/api/sample/    
curl -i -H "Accept: application/json" -H "X_REST_USERNAME: admin@restuser" -H "X_REST_PASSWORD: admin@Access" http://yii-tester.local/api/sample/limit/1
curl -i -H "Accept: application/json" -H "X_REST_USERNAME: admin@restuser" -H "X_REST_PASSWORD: admin@Access" http://yii-tester.local/api/sample/limit/10/5 (limit/offeset)

Current error response, which totally makes sense..:

{
    "success": false,
    "message": "You are not authorized to proform this action.",
    "data": {"errorCode":500}
}

Does anyone have a clue how to send such values throughout Backbone?

like image 925
Sjaak Rusma Avatar asked Nov 03 '22 10:11

Sjaak Rusma


1 Answers

Backbone delegates its XHR requests to jQuery/Zepto, that's what you will have to modify.

The easiest solution is probably to provide defaults options via $.ajaxSetup and the headers options

headers(added 1.5)
Default: {}

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

You would set it like this:

$.ajaxSetup({
    headers:{
        X_REST_USERNAME: "admin@restuser",
        X_REST_PASSWORD: "admin@Access"
    }
});

Every request sent will have the custom headers. See http://jsfiddle.net/nikoshr/j5Rr4/

Or you could pass additional options to each requests, Backbone will forward them to jQuery:

var m = new Backbone.Model();   
m.fetch({
    headers:{
        X_REST_USERNAME: "admin@restuser",
        X_REST_PASSWORD: "admin@Access"
    }
});

http://jsfiddle.net/nikoshr/j5Rr4/2/

Finally, you could override Backbone.sync to add the headers for every request:

Backbone.realsync = Backbone.sync;
Backbone.sync = function(method, model, options) {
    options || (options = {});
    options.headers = {
        X_REST_USERNAME: "admin@restuser",
        X_REST_PASSWORD: "admin@Access"
    };

    return Backbone.realsync.call(model, method, model, options);
};

var m = new Backbone.Model();
m.fetch();

http://jsfiddle.net/nikoshr/j5Rr4/4/

like image 145
nikoshr Avatar answered Nov 08 '22 06:11

nikoshr