【发布时间】:2016-07-18 05:31:12
【问题描述】:
在我的 rails 4 应用程序中,对于 html 和 js 请求,我想用 html 回复。在请求为html 的那一刻,渲染工作正常,但当请求为js 时,html 文件不会在屏幕上呈现(尽管在命令行中它说它已呈现)。
限制请求有不同的场景,因此 html POST 和 js POST 请求也可以触发节流代码。
Rack::Attack.throttle(key, limit: from_config(key, :limit), period: from_config(key, :period)) do |req|
if req.path.ends_with?(from_config(key, :path).to_s) && from_config(key, :method) == req.env['REQUEST_METHOD']
### This is the snippet I try to change the req type with but not working
if req.media_type == 'application/javascript'
req.media_type = 'text/html'
end
##### till here
req.ip
end
end
这是我要渲染的内容。如您所见,这是html 响应。
Rack::Attack.throttled_response = lambda do |env|
[429, {}, [ActionView::Base.new.render(file: 'public/429.html', content_type: 'text/html')]]
end
我该怎么办?
更新
这是我的最新版本,但不知道如何检查请求内容类型:
Rack::Attack.throttled_response = lambda do |env|
retry_after = (env['rack.attack.match_data'] || {})[10]
if env['rack.attack.content_type'] == 'text/html'
[429, {'Retry-After' => retry_after.to_s}, [ActionView::Base.new.render(file: 'public/429.html', content_type: 'text/html')]]
elsif env['rack.attack.content_type'] == 'application/javascript'
[429, {'Retry-After' => retry_after.to_s}, window.location.href = '/429.html']
end
end
【问题讨论】:
-
你到底为什么要这么做?创建自定义 mime 类型或使用标头检查它是否是 XHR 请求而不是弄乱现有的 mime 类型之一会更有意义。
-
如果请求包含
accept: text/html以外的内容,大多数浏览器也不会将响应呈现为 HTML。 -
max,你能告诉我怎么做吗?我不知道为什么这会搞砸任何事情,因为只有当 sby 超过某些操作的限制时才会发生这种情况。
-
我有点错过了关于节流的部分,你真的需要/想要返回一个 html 响应吗?如果客户端已被限制,您应该返回
429和空白响应或包含注释的 javascript,以免破坏实际上可能期望 JS 响应的客户端,并将尝试将响应解析为 javascript。 -
作为一名开发人员,我会发现这比我的脚本因漂亮的错误页面而炸毁要有用得多。
标签: ruby-on-rails mime-types rack rackattack