簡體   English   中英

Ruby On Rails before_filter調用過兩次嗎?

[英]Ruby On Rails before_filter called twice?

當我向我的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

RoR對ajax請求的響應

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秒,這表明您的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. 我不認為Rails會在不被調用的情況下觸發兩次控制器操作

因此,您必須查看問題的各個要素:


首先,您的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掛鈎page: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 發送到服務器“網絡”請求來備份:

在此處輸入圖片說明


最后,您需要在沒有before_filter方法的情況下進行一些測試,以查看是否可行。 也許您在中間件中沒有正確的真實性令牌或其他問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM