设计ajax sign_in

时间:2016-12-12 18:31:25

标签: ruby-on-rails json ajax devise

我试图通过devise制作ajax sign_in,我按照tutorial进行操作。

我已成功创建了一个ajax sign_up。这是我的registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  respond_to :json
  skip_before_filter :verify_authenticity_token, :only => :create
end

它工作正常,但在sign_in中失败。

这是我的session_controller.rb

class SessionsController < Devise::SessionsController
  respond_to :json
end

参数和路径就像这样

路径:/users/sign_in 参数:

{
  "user": 
  {
    "email": "123@gmail.com",
    "password":"12345678",
    "remember_me":"1"
  },
  "commit":"Log in"
}

但是我收到了这个错误。

enter image description here

更新

我还有401 Unauthorized。我尝试过以下方式。

1.编辑 application_controller.rb protect_from_forgeryprotect_from_forgery with: :null_session

2.在 sessions_controller.rb

中添加skip_before_filter :verify_authenticity_token, :only => :create

3.将我的ajax修改为此

$.ajax ({
      headers: {
        'X-Transaction': 'POST Example',
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
      },
      url: "sign_in",
      type: "POST",
      dataType: 'json',
      data: {
        "user": {"email": "example@gmail.com", "password": "password"}
      },
      success: function(msg){
        console.log("Success");
      },
      error: function(msg) {
        console.log("Errors");
      }
});

但是,所有人都犯了同样的错误。

Started POST "/users/sign_in" for ::1 at 2016-12-14 01:13:09 +0800
Processing by SessionsController#create as JSON
  Parameters: {"user"=>{"email"=>"example4@gmail.com", "password"=>"[FILTERED]"}, "commit"=>"Log in"}
  User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`email` = 'example4@gmail.com' ORDER BY `users`.`id` ASC LIMIT 1
Completed 401 Unauthorized in 2ms (ActiveRecord: 0.3ms)

1 个答案:

答案 0 :(得分:0)

我相信缺少CSRF令牌......您在以下教程中也说明了这一点:http://blog.andrewray.me/how-to-set-up-devise-ajax-authentication-with-rails-4-0/#maketheajaxrequests

尝试在application_controller.rb protect_from_forgeryprotect_from_forgery with: :null_session

中进行修改
相关问题