gpt4 book ai didi

ruby-on-rails - 如何处理来自 Rails 中应用程序 Controller 的无效真实性 token json 请求

转载 作者:行者123 更新时间:2023-12-02 09:22:13 25 4
gpt4 key购买 nike

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

"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 请求。

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

我的 Rails 版本是 4.2

最佳答案

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

respond_to do |format|
format.json { render json: true }
end

关于ruby-on-rails - 如何处理来自 Rails 中应用程序 Controller 的无效真实性 token json 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53337404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com