3

当用户尝试使用脚本或自动化填写表单时,应用程序控制器会引发错误

“ActionController::InvalidAuthenticityToken”

当有效的真实用户填写表单、关闭浏览器、从浏览器历史记录中重新打开页面并提交表单时,就会发生这种情况。

在这种情况下,我不想使用异常通知器发送异常,并且我还想显示带有刷新的请求消息的模式。

所以我将application_controller修改为

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  rescue_from ActionController::InvalidAuthenticityToken, with: :handle_csrf_error

  def handle_csrf_error(exception)
    respond_to do |format|
      format.js {
        render 'invalid_requests/error'
      }
      format.html {
        render text: I18n.t('errors.messages.csrf_error')
      }
    end
    ExceptionNotifier.notify_exception(exception)
  end

end

我想让它适用于所有类型的请求。

我添加了对 html & js 请求的响应

但没有得到如何处理 json 请求。

PS > json 请求是从 Web 应用程序发送的,用于加载更多案例,有时会引发异常,所以我要处理这个。

我的 Rails 版本是 4.2

4

2 回答 2

0

在确保您的请求正确地发出json请求而不是请求之后js(检查您的Content-Type标题)。添加一个format.json到您的服务器响应

respond_to do |format|
  format.json { render json: true }
end
于 2018-11-18T22:14:28.663 回答
0

关闭控制器中对真实性令牌的检查。

skip_before_action :verify_authenticity_token

http://stackoverflow.com/questions/1177863/ddg#1177883

于 2018-11-18T23:18:09.580 回答