Emilio
Emilio

Reputation: 1044

Custom http headers with JsonRest Store (dojo)

I was wondering if there's any way to set my own custom http headers in the Get ajax request (xhr.get) that automatically does a JsonRest store.

There's a related topic but without a great solution: Dojo Data grid with custom HTTP headers

I've seen the JsonRest implementation in 'dojo.store.JsonRest' including the constructor, and it's not obvious if we can do it or not (but I don't think so). Example of JsonRest store in use:

var store = new JsonRestStore({target: "/Table/" });

Upvotes: 4

Views: 1714

Answers (1)

phusick
phusick

Reputation: 7352

I would accomplish it subclassing dojo.store.JsonRest as you can see in this jsFiddle.

A. Subclass dojo.store.JsonRest:

var MyJsonRest = declare(JsonRest, {

    get: function(id, options) {
        return this.inherited(
            arguments,
            [id, lang.mixin(this.defaultGetHeaders, options)]
        );
    }
});

So you override get method calling superclass' get, but the second argument options (ie. headers) will now contain also properties from this.defaultGetHeaders.

B. Define defaultGetHeaders in the constructor:

var myJsonRest = MyJsonRest({
    target: "/echo/json/",
    defaultGetHeaders: {
        userId: "xyz",
        requestedBy: "abc",
        requestedFrom: "123"            
    }        
});

C. Calling myJsonRest.get() method you can also overwrite default headers:

myJsonRest.get("someId", { requestedFrom: "321"}).then(function(result) {
    console.log(result);        
});

D. Check request headers:

enter image description here

Upvotes: 7

Related Questions