$http进入 Rails 应用控制器提供针对角度 1.1+ 构建的"HTTP Error 406 Not acceptable"



如果你像这样调用Rails服务:

 $http.get(url).success(successFn)
               .error(
                      function(data, status, headers, config) {
                               console.log('Failed');
                      }
                     );

你的Rails ApplicationController像这样响应:

   def your_service
      # do some stuff
      respond_to do |format|
         format.js { render 'shared/common_js' }
      end
   end

使用angular 1.0。一切都很顺利,你的服务回答OK 200。

然后我对不稳定的1.1尝试了相同的代码。

我花了几个小时调查这个问题,希望这能节省别人的时间。

经过调试会话后,我终于发现差异在请求头:

1.0.3 (at this time):  {X-Requested-With: "XMLHttpRequest", Accept: "application/json, text/plain, */*", X-XSRF-TOKEN: undefined} 
1.1.1 (at this time):  {Accept: "application/json, text/plain, */*", X-XSRF-TOKEN: undefined} 

所以我谷歌了"X-Requested-With: XMLHttpRequest removed",我终于发现了这个提交:

($http):从标头默认值中删除'X-Requested-With'https://github.com/angular/angular.js/commit/3a75b1124d062f64093a90b26630938558909e8d

(这个删除是一些讨论的结果,基本上意味着允许更流畅的CORS请求)

删除

后,Rails无法再找到贯穿服务的路径,即:

format.js { render 'shared/common_js' }  

不再被触发(实际上是format.html)!

    $http( {method: 'GET', url: url , headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*'}})
           .success(successFn)
           .error(
                           function(data, status, headers, config) {
                               console.log('Fail');
                             }
                         );

否则,如提交中所述,您可以像这样找回丢失的头:

myAppModule.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

希望对大家有帮助。

最新更新