在 Sinatra 中过滤之前导致重定向循环
Before filter in Sinatra causing a redirect loop
我有这个简单的代码:
require 'sinatra'
before do
redirect '/login'
end
get '/login' do
'hello'
end
get '/test' do
'should not show'
end
这个简单的应用程序应该重定向每条路线,包括 /test
到 login
路线。相反,我得到了一个重定向循环。
我用的是最新版的Sinatra 2.0.5
您需要从 before_filter
中排除 /login
路线
before do
redirect '/login' if request.path_info != "/login"
end
上面提供了一个解决方案,但解释是redirect
触发了浏览器重定向,因此该过程每次都会在开始时重新开始。要使用服务器端重定向,请使用 call
。来自 the docs:
Triggering Another Route
Sometimes pass is not what you want, instead you would like to get the
result of calling another route. Simply use call to achieve this:
get '/foo' do
status, headers, body = call env.merge("PATH_INFO" => '/bar')
[status, headers, body.map(&:upcase)]
end
get '/bar' do
"bar"
end
Note that in the example above, you would ease testing and increase
performance by simply moving "bar" into a helper used by both /foo and
/bar.
If you want the request to be sent to the same application instance
rather than a duplicate, use call! instead of call.
Check out the Rack specification if you want to learn more about call.
因此,您可能需要一个助手(或者更可能需要一个 条件,如果您正在检查身份验证)。
我有这个简单的代码:
require 'sinatra'
before do
redirect '/login'
end
get '/login' do
'hello'
end
get '/test' do
'should not show'
end
这个简单的应用程序应该重定向每条路线,包括 /test
到 login
路线。相反,我得到了一个重定向循环。
我用的是最新版的Sinatra 2.0.5
您需要从 before_filter
中排除/login
路线
before do
redirect '/login' if request.path_info != "/login"
end
上面提供了一个解决方案,但解释是redirect
触发了浏览器重定向,因此该过程每次都会在开始时重新开始。要使用服务器端重定向,请使用 call
。来自 the docs:
Triggering Another Route
Sometimes pass is not what you want, instead you would like to get the result of calling another route. Simply use call to achieve this:
get '/foo' do
status, headers, body = call env.merge("PATH_INFO" => '/bar')
[status, headers, body.map(&:upcase)]
end
get '/bar' do
"bar"
end
Note that in the example above, you would ease testing and increase performance by simply moving "bar" into a helper used by both /foo and /bar.
If you want the request to be sent to the same application instance rather than a duplicate, use call! instead of call.
Check out the Rack specification if you want to learn more about call.
因此,您可能需要一个助手(或者更可能需要一个 条件,如果您正在检查身份验证)。