Ruby On Rails before_filter调用了两次?

时间:2015-10-08 08:32:42

标签: javascript ruby-on-rails ruby ajax controller

当我向我的ruby控制器发送ajax请求时,似乎每个ajax请求都会调用before_filter函数两次。我使用before_filter进行身份验证。

我使用的ajax请求

 $.ajax({
    type: 'GET',
    url: 'URL_TO__RoR_Controller',
    username: username,
    password: password,
    contentType: "application/json; charset=utf-8",
    success: function(data){
      console.log(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
      console.log(arguments);
    }
  });

RoR代码

class Api::MyController < ApplicationController
before_filter :authenticate
attr_reader :current_user

def authenticate
print "===================================\n"
authenticate_or_request_with_http_basic do |username, password|
  print "\n--------------------------------\n"
  print username, password
  print "\n--------------------------------\n"
  @current_user = User.authenticate(username, password)
  print "===================================\n"
end
end

def show
 print "=================IN SHOW=================="
end
end

对ajax请求的RoR响应

Started GET "URL_TO__RoR_Controller" for 127.0.0.1 at 2015-10-08 10:18:18 +0200
Processing by Api::MyController#show as JSON
  Parameters: {"id"=>"show", "test"=>{}}
===================================
===================================
Filter chain halted as :authenticate rendered or redirected
Completed 401 Unauthorized in 1ms (ActiveRecord: 1.0ms)


Started GET "URL_TO__RoR_Controller" for 127.0.0.1 at 2015-10-08 10:18:19 +0200
Processing by Api::MyController#show as JSON
  Parameters: {"id"=>"show", "test"=>{}}
===================================

--------------------------------
USERPASS
--------------------------------
  User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`authorized` = 1 AND `users`.`login` = 'USER' LIMIT 1
===================================
=================IN SHOW==================
  Rendered URL_TO__RoR_Controller/show.json.rabl (0.8ms)
Completed 200 OK in 30ms (Views: 3.4ms | ActiveRecord: 1.7ms)

此单一控制器的RoR config / routes.rb

Api::Application.routes.draw do
 namespace :api, defaults: { format: :json } do
      resources :MyController, only: [:show]
  end
 end

基本上,对于我发送的每个ajax请求,authenticate函数似乎执行了两次。第一次身份验证似乎失败了。它甚至没有进入authenticate_or_request_with_http_basic功能。一切似乎都很好。

显然这不是理想的行为。是什么导致了这个问题?

修改:

好的,这是我在删除before_filter时的发现:

1)完全删除before_filter后,问题不再发生。

2)保持/使用before_filter但用'true'替换authenticate_or_request_with_http_basic时:

def authenticate
 true
end 

问题也没有发生。所以问题似乎是由authenticate_or_request_with_http_basic引起的?

1 个答案:

答案 0 :(得分:0)

除非以某种方式调用,否则不会发生这种情况。

看到请求在彼此之间发送1秒,它表明您的Ajax被发送了两次:

127.0.0.1 at 2015-10-08 10:18:18 +0200
127.0.0.1 at 2015-10-08 10:18:19 +0200

虽然这本身不是一个答案,但你可以做很多事情来“调试”它:

  
      
  1. 首先,您必须明白不会发生
  2.   
  3. “调试”过程只是识别正在发生的事情的一个案例。解决它
  4.   
  5. 我不认为Rails会在没有调用的情况下触发控制器动作两次
  6.   

因此,您必须查看问题的各个要素:

首先,你的 Ajax 请求似乎被解雇了两次。

您提供了以下代码:

$.ajax({
    type: 'GET',
    url: 'URL_TO__RoR_Controller',
    username: username,
    password: password,
    contentType: "application/json; charset=utf-8",
    success: function(data){
      console.log(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
      console.log(arguments);
    }
});

告诉我们它如何绑定到您网页上的元素。我推测你遇到了Turbolinks的问题。

调试的第一步是确保您的JS绑定不受阻碍。具体来说,您希望确保利用turbolinks hookspage:load):

#app/assets/javascripts/application.js
bind = function() {
   $(".element").on("click", function() {
      // Ajax
   });
};
$(document).on("ready page:load", bind);

或者您可以从文档中委派:

#app/assets/javascripts/application.js
$(document).on("click", ".element", function() {
     // Ajax
});

其次,您的控制器操作似乎被调用了两次,但它不仅仅是before_filter ...它是整个流程(在第二个实例中)。

Filter chain halted as :authenticate rendered or redirected
Completed 401 Unauthorized in 1ms (ActiveRecord: 1.0ms)

第一个before_filter未触发的唯一原因是您未经过身份验证。我不知道你是如何对用户进行身份验证的,但是如果你能够做到这一点,我会认为流程会发生。

那么问题就变成了你是如何得到第一个被退回的请求

如果你在两个请求之间做了不同的事情,我们需要看到它。不是我认为你知道,它是自动完成的:)

-

可以通过使用ajax:

观察"network" requests sent to the server来备份

enter image description here

最后,您希望在没有before_filter方法的情况下进行一些测试,看看是否可行。也许你没有在中间件中获得正确的真实性令牌或其他问题。

相关问题