BackBone client with a remote Rails Server

后端 未结 3 1773
面向向阳花
面向向阳花 2021-02-06 18:57

Background:

I use \"rails g scaffold hotel name stars:integer\" to start fast (and insert into the database some records), and write a Backbone client

3条回答
  •  青春惊慌失措
    2021-02-06 19:55

    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*,/
    

    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");
        }
      });
    });
    

提交回复
热议问题