How to get cookie values ​​in backbone.js model?

I have a simple Backbone.js / Bootstrap front end in HTML5 with Node.js / Restify backend. I set cookies in the header response from the server as shown below:

res.setHeader("Set-Cookie", ["token=ninja", "language=javascript"]);

On the client side, I am making a REST call as

var response = this.model.fetch().success(function(data){
           //success
           }).error(function(data){
           //error 
           }).complete(function(data){
            //complete
           });

which calls the analysis method in the model.

How can I read the cookie value in the model?

+3
source share
3 answers

Enable Cookie.js .

You can then link to individual cookies as follows:

var token = Cookie.get('token')

# token == 'ninja'
+1
source

. : HTML/js , REST- (, , .) cookie REST, , . , - cookie, . - cookie , http://backbonetutorials.com/cross-domain-sessions/.

+1

Assuming you are using jQuery with a Backbone, you can get the headers by specifying a function parsein your model by calling getAllResponseHeadersor getResponseHeader:

var model = Backbone.Model.extend({

    // the rest of your model

    parse: function(resp, xhr) {
        var allHeaders = xhr. getAllResponseHeaders();
        var cookieHeader = xhr. getResponseHeader("Set-Cookie");

        // do something with the headers

        return resp;
    }
});
0
source

All Articles