如果由于某种原因无法创建用户,我会在注册 Controller 中使用 devise 进行身份验证,然后它会生成 json 响应作为
{"email":["has already been taken"],"password":["doesn't match confirmation"],"username":["has already been taken"]}
但我希望将其更改为以下内容
{"error":{"email":{"has already been taken"},"password":{"doesn't match confirmation"},"username":{"has already been taken"}}}
我该怎么做?
最佳答案
作为引用,以防其他人在使用 Devise 尝试登录失败时寻找如何自定义 json 错误响应时偶然发现这个问题,关键是使用您自己的自定义 FailureApp
实现. (您也可以使用这种方法来覆盖某些重定向行为。)
class CustomFailureApp < Devise::FailureApp
def respond
if request.format == :json
json_error_response
else
super
end
end
def json_error_response
self.status = 401
self.content_type = "application/json"
self.response_body = [ { message: "Your email or password is incorrect."} ].to_json
end
end
在您的 devise.rb
中,查找 config.warden
部分:
config.warden do |manager|
manager.failure_app = CustomFailureApp
end
一些相关信息:
起初我以为我必须重写Devise::SessionsController ,可能使用传递给 warden.authenticate!
的 recall
选项,但如前所述 here , "recall 不会为 API 请求调用,只会为导航请求调用。如果您想自定义 http 状态代码,那么在失败的应用程序级别这样做会更好。"
关于ruby-on-rails - 如何将设计中的默认 json 响应更改为自定义响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13577969/