简体   繁体   English

Laravel angularjs Request :: ajax()总是假的

[英]Laravel angularjs Request::ajax() always false

I'm building application with angularjs and laravel 4. Everything is fine but I need now to allow only XHR requests. 我正在用angularjs和laravel构建应用程序4.一切都很好但我现在只需要允许XHR请求。

This is what I have at the beginning of my controller. 这就是我在控制器开头所拥有的。 But this statement is always false. 但这种说法总是错误的。

    if (!\Request::ajax())
    {
        return Response::json(array('halt'=>Request::ajax()));
    };

In angular I'm using standard $http service. 在角度我使用标准的$ http服务。

angular.module('APP')
.factory("API", ($http,$q,appClient,apiURL) ->
 class FB
  constructor:->
    this.deferredData = $q.defer();
  info: (reload)->
    $http(
      method: "get"
      url: apiURL+'game/'+appClient+"/info"
    ).success((res)->
      dostuff()
    )

When doing AJAX calls, the X-Requested-With header is often set to XMLHttpRequest . 在进行AJAX调用时, X-Requested-With标头通常设置为XMLHttpRequest Laravel's Request::ajax() method is built on top of a Symfony2 method that simply checks for the presence of this header. Laravel的Request::ajax()方法构建在Symfony2方法之上,该方法只检查此标头的存在。

In October 2012, Angular.js removed this header because they felt that it was rarely used. 2012年10月,Angular.js 删除了这个标题,因为他们觉得很少使用它。

As @Thrustmaster and yourself mentioned in the comments, you need to set: 正如@Thrustmaster和您在评论中提到的那样,您需要设置:

$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"

If you'd rather not modify the front-end angular application (or can't), and would rather modify your Laravel code to differentiate between Angular JS AJAX requests vs. other requests, you can also use Request::wantsJson() : 如果您不想修改前端角度应用程序(或者不能),并且宁愿修改Laravel代码以区分Angular JS AJAX请求与其他请求,您还可以使用Request::wantsJson()

if(Request::wantsJson()) {
    // Client wants JSON returned 
} else {
    // Client does not want JSON returned
}

The wantsJson method relies on the standard Accepts HTTP header (rather than the non-standard X-Requested-With header) for the presence of application/json . wantsJson方法依赖于标准的Accepts HTTP标头(而不是非标准的X-Requested-With标头)来存在application/json As long as Angular JS leaves that in by default and you don't remove it on purpose, this method should be reliable. 只要Angular JS默认将其保留,并且您没有故意删除它,此方法应该是可靠的。

For AngularJs newbies looking for where to add $httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest" 对于AngularJs新手寻找添加$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"

Here is an example: 这是一个例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM