2016-06-10 38 views
0

我在我的視圖中創建一個AJAX週期性地發送數據:無效的真實性令牌

$.ajax({ 
     type: "PATCH", 
     url: "/drivers/" + <%= current_user.id %> + "/coordinates", 
     data: data, 
     success: postSuccess 
}); 

到:

def update 
    if @driver.update_attributes(driver_params) 
     head :ok 
    else 
     render status: :unprocessable_entity, json: { 
     error: @driver.errors 
     } 
    end 
    end 

,這似乎很好地工作的大部分時間。然而,有時它會返回:

An ActionController::InvalidAuthenticityToken occurred in drivers#coordinates 


Request: 
------------------------------- 

    * URL  : 
    * HTTP Method: PATCH 
    * IP address : 
    * Parameters : {"latitude"=>"59.9", "longitude"=>"10.77", "controller"=>"drivers", "action"=>"coordinates", "id"=>"16"} 
    * Timestamp : 2016-06-10 17:55:56 +0200 
    * Server : 
    * Rails root : /var/deploy/ 
    * Process: 6997 

------------------------------- 
Session: 
------------------------------- 

    * session id: [FILTERED] 
    * data: {"session_id"=>"b08d5d2604631c91fc2db202", 
    "_csrf_token"=>"3seCLYJYUuUX0JWlU8Z83frEE3HxA="} 

這很奇怪,因爲80%的時間這個工作完美。也許是它觸發它的更新速度,說實話我不確定。通常,用戶位於單個頁面上,並在後臺運行並更新其GEO座標。

有沒有人有關於如何解決這個問題的想法?有沒有辦法添加一個適用於AJAX的真實性標記,如果它能工作多次(因爲這可以在同一頁面上觸發50-100次)。

回答

0

如果你看一下錯誤通知,它生成此異常InvalidAuthenticityToken

這意味着你觸發了您的POST/PATCH請求沒有身份驗證令牌在默認情況下在ApplicationController中

protect_from_forgery with: :exception 

定義你需要這些PARAMS裏面做:

Parameters : {"latitude"=>"59.9", "longitude"=>"10.77", "controller"=>"drivers", "action"=>"coordinates", "id"=>"16"} 

添加令牌通過查看標籤生成:

<%= csrf_meta_tag %> 

如果您使用jquery你可以抓住這樣的

$('meta[name=csrf-token]').attr('content'); 

您可以關閉CSRF保護,但我不會reccomend除非你使用純JSON API。相反,當你做$ .ajax時,將它添加到你的參數中。您可以使用類似這樣

$.ajaxSetup({ 
headers: { 
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') 
    } 
}); 

或裏面你Ajax調用

$.ajax({ 
... 
    beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token',$('meta[name="csrf-token"]').attr('content'))} 
...