How use token authentication with Rails, Devise and Backbone.js?

后端 未结 3 1084
旧时难觅i
旧时难觅i 2020-12-07 08:10

I\'m trying to build a mobile application with PhoneGap, jQuery Mobile and Backbone.js on the client-side - with a Rails 3 JSON API running server-side.

I know how t

3条回答
  •  一向
    一向 (楼主)
    2020-12-07 08:56

    The key is to introduce it in the Backbone.sync method.

    Take a look at this implementation: https://github.com/codebrew/backbone-rails/blob/master/vendor/assets/javascripts/backbone_rails_sync.js

    You can add it yourself this way:

    Backbone.old_sync = Backbone.sync
    Backbone.sync = function(method, model, options) {
        var new_options =  _.extend({
            beforeSend: function(xhr) {
                var token = $('meta[name="csrf-token"]').attr('content');
                if (token) xhr.setRequestHeader('X-CSRF-Token', token);
            }
        }, options)
        return Backbone.old_sync(method, model, new_options);
    };
    

    Check out this fiddle: http://jsfiddle.net/dira/ZcY3D/14/

提交回复
热议问题