ruby-on-rails - $http get to a Rails ApplicationController 针对 angular 1.1+ 构建给出 "HTTP Error 406 Not acceptable"

标签 ruby-on-rails http-headers angularjs

很难说出这里问的是什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或言辞激烈,无法以目前的形式合理回答。如需帮助澄清此问题以便可以重新打开,visit the help center .




8年前关闭。




如果您像这样调用 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.x 一切顺利,您的服务回答 OK 200。

然后我针对不稳定的 1.1.x 版本尝试了相同的代码,结果停止工作,HTTP 错误 406 Not Acceptable 。

最佳答案

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

经过调试 session ,我终于发现不同之处在于请求 header :

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):从 header 默认值中删除“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');
                             }
                         );

否则,如提交中所述,您可以像这样带回丢失的 header :
myAppModule.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

希望这有帮助,干杯。

关于ruby-on-rails - $http get to a Rails ApplicationController 针对 angular 1.1+ 构建给出 "HTTP Error 406 Not acceptable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14210218/

相关文章:

api - 处理禁止的 REST 请求 403 与 404

python - Django 测试客户端 : How to remove http headers

javascript - 返回嵌套 Promise 时无法读取未定义的属性 'then'

javascript - 如何在AngularJS中全屏显示谷歌地图

ruby-on-rails - 如何使用 Devise Token Auth 通过 API 更改密码? rails 5

ruby-on-rails - 无法识别 ubuntu 终端中的 rails ,但在 aptana 终端中

python - 使用 Python/Selenium/Best Tool For The Job 获取通过 JavaScript 生成的图像请求的 URI?

angularjs - ng-sortable 如何在项目重新排序时获取列表 id

ruby-on-rails - Spree 模块装饰器

ruby-on-rails - RSpec + 回形针 : identify: no decode delegate for this image format