簡體   English   中英

如何使用AJAX JSON響應來響應CanCan :: AccessDenied?

[英]How do I respond to CanCan::AccessDenied with an AJAX JSON response?

如果請求是通過AJAX進行的,我想用JSON響應CanCan::AccessDenied ,但是無論如何它始終以狀態200和重定向進行響應。 我想實現此答案: https : //stackoverflow.com/a/10013873/148844 我不知道它是如何將狀態302覆蓋為200,更不用說不呈現JSON了。 我也嘗試過format.js但這format.js

application_controller.rb
class ApplicationController < ActionController::Base
  include CanCan::ControllerAdditions

  rescue_from CanCan::AccessDenied do |exception|
    flash[:warning] = exception.message
    logger.info exception
    respond_to do |format|
      logger.info "format: " + format.to_s
      format.html do
        if user_signed_in? && current_user.type
          redirect_to "/dashboard"
        else
          redirect_to root_path
        end
      end
      format.json do
        render json: {success: false, message: 'Access Denied: '+exception.message}, status: 401
      end
    end
  end
CoffeeScript
$.post "/topics/order", {'id_order[]': arr}, (data, textStatus, jqXHR) ->
  ...
Gemfile
gem 'cancancan', '~> 1.10'
Console
Started POST "/topics/order" for ::1 at 2018-09-14 14:44:33 -0400
...
You are not authorized to access this page.
format: #<ActionController::MimeResponds::Collector:0x0000000d4b2a28>
Redirected to http://localhost:3000/dashboard
Completed 200 OK in 314ms (ActiveRecord: 28.0ms)

https://github.com/CanCanCommunity/cancancan#4-handle-unauthorized-access

https://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_to


我做了一些測試並添加了

  format.json { head :forbidden, content_type: 'text/html' }
  format.js   { head :forbidden, content_type: 'text/html' }

respond_to塊的頂部,它確實起作用。 當移動到塊的底部時,它不起作用。 無論采用哪種format ,Rails似乎都會對它看到的第一種format做出響應!

我將json作為dataType添加到帖子中,現在可以正常工作了。

$.post "/topics/order", {'id_order[]': arr}, (data, textStatus, jqXHR) ->
  ...
, 'json'

https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings

dataType(默認值:Intelligent Guess(xml,json,腳本或html))
類型:字符串
您期望從服務器返回的數據類型。 如果未指定,則jQuery將嘗試根據響應的MIME類型來推斷它(XML MIME類型將產生XML,在1.4中,JSON將產生JavaScript對象,在1.4中,腳本將執行該腳本,而其他所有內容將是以字符串形式返回)。 可用的類型(以及作為第一個參數傳遞給您的成功回調的結果)是:

"json" :將響應評估為JSON並返回一個JavaScript對象。 具有回調占位符(例如?callback =?)的跨域“ json”請求是使用JSONP執行的,除非該請求在其請求選項中包含jsonp:false。 JSON數據是嚴格解析的。 任何格式錯誤的JSON都會被拒絕,並引發解析錯誤。 從jQuery 1.9開始,空響應也被拒絕; 服務器應返回null或{}的響應。 (有關正確的JSON格式的更多信息,請參見json.org。)

暫無
暫無

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

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