问题
In my rails 4 app I'd like to response with html
both for html
and js
request. At the moment when the request is html
type the rendering works fine, but when the request is js
then the html file doesn't get rendered on the screen (although in the command line it says it's rendered).
There are different scenarios for limiting requests so the throttle code can be triggered by html POST
and js POST
request as well.
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
Here is what I'm trying to render. As you see this is html
response.
Rack::Attack.throttled_response = lambda do |env|
[429, {}, [ActionView::Base.new.render(file: 'public/429.html', content_type: 'text/html')]]
end
What should I do?
UPDATE
This is my newest version, but can't figure out how to check the request content_type:
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
docs: https://github.com/kickstarter/rack-attack
回答1:
I agree with @max. In principle, you should not respond with HTML to a request specifically for JS.
But to answer this part of the question:
how to check the request content_type:
Try checking this instead:
req.env['HTTP_ACCEPT']
Explanation
req
is an object that subclassesRack::Request
.- Rack prepends
HTTP_
to the client's HTTP request headers and adds them to theenv
hash. - HTTP clients can indicate what MIME types they accept in the
Accept
header, as opposed to theContent-Type
header, where they can indicate what type of data they are sending to you.
来源:https://stackoverflow.com/questions/36304993/sync-rack-request-and-response