Sinatra 1.0 中过滤器块后无法访问内部的response.body
我正在努力解决一个奇怪的问题。根据 http://github.com/sinatra/sinatra (部分过滤器),响应对象可在Sinatra 1.0 中的过滤器块之后。但是,response.status 可以正确访问,但我在过滤器后的路由中看不到非空的response.body。
我有这个rackup文件:
config.ru
require 'app'
run TestApp
然后使用Sinatra 1.0.b gem安装:
gem install --pre sinatra
这是我的带有单个路由的小应用程序:
app.rb
require 'rubygems'
require 'sinatra/base'
class TestApp < Sinatra::Base
set :root, File.dirname(__FILE__)
get '/test' do
'Some response'
end
after do
halt 500 if response.empty? # used 500 just for illustation
end
end
现在,我想要访问后过滤器内的响应。当我运行此应用程序并访问 /test URL 时,我收到 500 响应,就好像响应为空一样,但响应显然是“某些响应”。
除了我对 /test 的请求之外,浏览器还向 /favicon.ico 发出了单独的请求,该请求返回 404,因为没有路由,也没有静态文件。但我希望返回 500 状态,因为响应应该为空。
在控制台中,我可以看到在后过滤器中,对 /favicon.ico 的响应类似于“未找到”,对 /test 的响应实际上是空的,即使路由返回了响应。
我想念什么?
I'm struggling with a strange issue. According to http://github.com/sinatra/sinatra (secion Filters) a response object is available in after filter blocks in Sinatra 1.0. However the response.status is correctly accessible, I can not see non-empty response.body from my routes inside after filter.
I have this rackup file:
config.ru
require 'app'
run TestApp
Then Sinatra 1.0.b gem installed using:
gem install --pre sinatra
And this is my tiny app with a single route:
app.rb
require 'rubygems'
require 'sinatra/base'
class TestApp < Sinatra::Base
set :root, File.dirname(__FILE__)
get '/test' do
'Some response'
end
after do
halt 500 if response.empty? # used 500 just for illustation
end
end
And now, I would like to access the response inside the after filter. When I run this app and access /test URL, I got a 500 response as if the response is empty, but the response clearly is 'Some response'.
Along with my request to /test, a separate request to /favicon.ico is issued by the browser and that returns 404 as there is no route nor a static file. But I would expect the 500 status to be returned as the response should be empty.
In console, I can see that within the after filter, the response to /favicon.ico is something like 'Not found' and response to /test really is empty even though there is response returned by the route.
What do I miss?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
response.body 设置为 Sinatra::Base#invoke,它包装了 Sinatra::Base#dispatch!,而 Sinatra::Base#dispatch! 又调用过滤器。但是,#invoke 在调度后设置响应正文!已完成,因此主体尚未设置。您想要做的事情可能可以通过机架中间件更好地解决。
The response.body is set Sinatra::Base#invoke, which wraps around Sinatra::Base#dispatch!, which in turn calls the filters. However, #invoke sets the response body after dispatch! is done, therefore the body is not yet set. What you want to do is probably better solved with a rack middleware.