更改状态码Rails [英] Change status code Rails
问题描述
我的处境非常糟糕.
我正在通过Ruby on Rails JSON API在Android应用程序上使用Volley.
I am using Volley on an Android application with Ruby on Rails JSON API.
问题是Volley有一个错误,使得它无法正确识别带有状态401的任何东西.基本上,只要状态为401,NetworkResponse就会为null,而VolleyError的类型为NoConnectionError.
Problem is there is a bug with Volley making it unable to correctly identify anything with staus 401. Basically, whenever there is a 401 status, the NetworkResponse is null and VolleyError is of type NoConnectionError.
我进行了很多搜索,唯一的解决方法是返回403,而不是由Volley可以正确识别的401.
I have searched a lot and the only way around it is to return 403 instead of 401 which can be identified correctly by Volley.
如何将所有响应的状态码更改为403(如果它们是401)?我无法控制所有动作,例如在设计预制动作时返回403.
How can I change status codes on all responses to 403 if they are 401 in rails? I can't control all the actions and return 403 for example in devise premade actions.
有没有一种方法可以最终确定响应或Rails中的某些东西?
Is there a way to finalize responses or something in rails?
推荐答案
我从 Ruby on Rails
后端找到了针对我的问题的解决方案,该解决方案针对整个应用程序是通用的许多控制器还会给出 401
,而不仅仅是 devise
.
I found a solution to my problem from the Ruby on Rails
backend side that is generalized for the whole application which is required as a lot of controllers would also give 401
and not only devise
.
我通过以下操作使用了 Rack
中间件:
I have used Rack
middleware by doing the following:
app/middleware/unauthorized_to_forbidden.rb
class UnauthorizedToForbidden
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
if(status == 401)
status = 403
end
[status, headers, response]
end
end
config/application.rb
class Application < Rails::Application
config.middleware.use "UnauthorizedToForbidden"
end
现在 UnauthorizedToForbidden
位于 Rack
堆栈的底部,并在将响应实际发送给用户之前在最后执行.如果将 401
更改为 403
,它将基本上更改状态代码.
Now UnauthorizedToForbidden
is at the bottom of the Rack
stack and gets executed at the very end before the response is actually sent to the user. It basically changes the status code if it's 401
to 403
.
这篇关于更改状态码Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!