【问题标题】:AngularJS $resource not sending X-Requested-WithAngularJS $resource 不发送 X-Requested-With
【发布时间】:2013-08-12 16:37:51
【问题描述】:

我正在使用 Angular 1.1.5,并且我正在使用 $resource 为 REST 服务创建 XHR,但似乎 $resource 没有将标头附加为 X-Requested-With 作为 XMLHttpRequest, 这是正常行为吗?我是否需要手动附加标头?

function loginCtrl($scope,$resource) {
    $scope.submit = function () {
         var resource = $resource('/Api/User/login', {},
              {
                  authenticate: {
                      method: 'POST',
                      isArray: false,
                      headers: {
                          '__RequestVerificationToken':  $scope.loginRequest.Token

                      }
                  }
              });
         resource.authenticate($scope.loginRequest);
    };
}

【问题讨论】:

  • $resource 不支持标头。您可能需要切换到使用 $http
  • 确实如此,我认为从 1.1.3 版开始
  • 我觉得你还是得在 $http 中设置,比如 $http.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
  • 实际上我可以像 headers: {'X-Requested-With': 'XMLHttpRequest'} 一样手动添加标头,它可以工作,但为什么默认情况下它不发送。
  • 想知道同样的事情:stackoverflow.com/a/19001632/33453

标签: angularjs xmlhttprequest


【解决方案1】:

我遇到了同样的问题,我使用以下方法解决了它:

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

您也可以将标头设置为接受application/json

$http({
  method: 'GET',
  url: '/someUrl',
  headers: { Accept: 'application/json' }
})

【讨论】:

    【解决方案2】:

    只需将此添加到您的应用中

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

    【讨论】:

    • Laravel 5.1 期望此标头将请求确定为“ajax 请求”。
    • 太好了,现在,我们如何在 Angular2 中做到这一点?
    • 我找了快一周了,当我评论的时候,我找到了答案:/angular.io/docs/ts/latest/api/http/…
    • 你需要这个,才能让 Asp.Net MVC 正确识别 Request.IsAjaxRequest()
    • @Ayyash 新链接?
    【解决方案3】:

    以前是,后来改了。 (see here)

    "X-Requested-With 标头在实践中很少使用,通过使用 我们一直在触发跨域的预检检查 请求。”

    来自 Thomas Pons 的回答 here

    【讨论】:

    • 很高兴知道,我正在使用它,因为我正在使用 servicestack 中的 antiForgeryToken 属性验证请求,问题是我验证为 ajax 请求至少知道该请求是由一个表单组成的,现在的问题是:“如果该请求是 ajax,我如何在服务器端知道?”,感谢您的回答!
    • 我会给你一个 +1 以获取对实际提交的额外参考。
    猜你喜欢
    • 2011-12-31
    • 2014-09-30
    • 1970-01-01
    • 2012-09-01
    • 2015-06-03
    • 1970-01-01
    • 2012-10-17
    • 2020-03-01
    相关资源
    最近更新 更多