简体   繁体   English

rails 如何确定传入的请求格式?

[英]How does rails determine incoming request format?

I'm just wondering how rails knows the format of the request as to correctly enter in the famous:我只是想知道 rails 如何知道正确输入著名的请求格式:

respond_to do |format|
  format.html
  format.xml
  format.json
end

As an example consider this situation I have faced up.作为一个例子,考虑一下我所面临的这种情况。 Suppose that via javascript (using jQuery) I make a POST request expliciting dataType: json假设通过 javascript(使用 jQuery)我发出一个 POST 请求,明确dataType: json

$.ajax({
      type: 'POST',
      url: 'example.com',
      data: data,
      dataType: 'json'
    });

When this request reach controller action, standing inside it with ruby debugger, I inspect @request.format and I can see that content-type is application/json.当这个请求到达 controller 动作时,用 ruby 调试器站在它里面,我检查@request.format,我可以看到内容类型是 application/json。 Then the controller respond to json format as expected.然后 controller 按预期响应 json 格式。

But I'm confused with the format symbol especified in the routes.但我对路线中指定的格式符号感到困惑。 Suppose that a request is made to example.com/parts.json but in the request the content type is application/html or application/xml.假设向example.com/parts.json发出请求,但请求中的内容类型是 application/html 或 application/xml。 Is the controller responding to json format or html or xml?? controller 是否响应 json 格式或 html 或 Z0F635D0E0F3874FFF7A7A726?

Thanks!谢谢!

From ActionController::MimeResponds : "Rails determines the desired response format from the HTTP Accept header submitted by the client."来自ActionController::MimeResponds :“Rails 从 HTTP 确定所需的响应格式,接受客户端提交的 header。”

The incoming Content-Type only affects the way the request is parsed.传入的Content-Type仅影响解析请求的方式。 It doesn't affect the response format.它不影响响应格式。

Since Rails 5.0 , the response format is determined by checking for: 从 Rails 5.0 开始,响应格式通过检查来确定:

  1. A format parameter (eg /url?format=xml ) format参数(例如/url?format=xml
  2. The HTTP Accept header (eg Accept: application/json ) HTTP Accept header (例如Accept: application/json
  3. The path extension (eg /url.html )路径扩展名(例如/url.html

You can see this in the implementation of ActionDispatch::Http::MimeNegotation#formats .您可以在ActionDispatch::Http::MimeNegotation#formats的实现中看到这一点。 Here is an excerpt from Rails v6.1:以下是 Rails v6.1 的摘录:

if params_readable?
  Array(Mime[parameters[:format]])
elsif use_accept_header && valid_accept_header
  accepts
elsif extension_format = format_from_path_extension
  [extension_format]
elsif xhr?
  [Mime[:js]]
else
  [Mime[:html]]
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM