且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

骨干客户端与远程服务器的Rails

更新时间:2022-06-21 22:14:12

要了解的重要一点是,在Rails的***做法是不使用的接受头。这里有一个很好的书面记录这可以解释为什么在光彩细致。总结是HTTP的浏览器的实现接受的头被打破了。 Rails的***做法是设定:在请求格式参数。不过,如果你喜欢他们所支持的接受头部但围绕什么是规则轨道的有效接受头可能会非常棘手。如果你接受的头相匹配的正则表达式如下:

The important thing to understand is that best practice in Rails is NOT to use the Accept headers. There is a nice writeup here that explains why in glorious detail. Summary is browser implementation of HTTP Accept headers is broken. Rails best practice is to set the :format parameter in the request. However, if you like the accept headers they are supported but the rules around what is a valid accept header in rails can be tricky. If your accept header matches the following regex:

BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/

然后栏杆它扔了出去,默认为text / html的MIME类型。我知道,对吧?你的头正好匹配这个。究其原因大多数人没有这个问题是轨修复,在铁轨的默认行为的jQuery的 jQuery的-UJS 。他们设置的JQuery一个ajaxSetup beforeSend回调放 * / * 在头开始,这是什么神奇的轨道正则表达式希望看到虽然我不能真的说不清为什么,除了他们知道未修改的浏览器请求会一直把它放在那里。这里是你将如何解决您在JQuery中接受头。

then rails throws it away and defaults to text/html mime type. I know, right? Your header happens to match this. The reason most people don't have this problem is that rails "fixes" the default jquery behavior in the rails jquery-ujs. They set a ajaxSetup beforeSend callback in JQuery that puts the */* at the beginning of the header, which is what the magic rails regex wants to see though I can't really tell why, other than they know that an unmodified browser request will always put it there. Here is how you might fix your accept header in JQuery.

$(function() {
  $.ajaxSetup({
    'beforeSend': function(xhr) {
    xhr.setRequestHeader("accept", "application/json");
    }
  });
});