sync rack request and response

我的未来我决定 提交于 2019-12-13 21:26:44

问题


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

  1. req is an object that subclasses Rack::Request.
  2. Rack prepends HTTP_ to the client's HTTP request headers and adds them to the env hash.
  3. HTTP clients can indicate what MIME types they accept in the Accept header, as opposed to the Content-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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!