Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$routeProvider: templateUrl requests with X-Requested-With header

jQuery.ajax() normally sends an X-Requested-With header with XMLHttpRequest set as the content. On the server (in PHP), I usually detect this by testing:

$is_ajax = $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'

In AngularJS, commonly found in $routeProvider.when(), you can obtain a template from the server with templateUrl: '/path/on/server'.

My problem is that templateUrl requests seem to not set X-Requested-With headers, so there's no way to distinguish templateUrl requests from any other type of request.

Is there any way to get $routeProvider to send X-Requested-With as XMLHttpRequest?

Reference:

  • $routeProvider Docs - (search templateUrl)

  • jQuery jqXHR - see jqXHR.setRequestHeader("X-Requested-With", "XMLHttpRequest")

  • Using Angular v1.1.5 via Google CDN

  • Update: I found the actual commit where Angular developers removed X-Requested-With from $http.get. Wonder why they would do that?

  • Update: https://github.com/angular/angular.js/issues/1004 - discussion where header was removed.

like image 815
tester Avatar asked Jul 20 '13 07:07

tester


1 Answers

Tip of the hat to Zerot in FreeNode's #angularjs

app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $routeProvider.when('/', {
        templateUrl: '/path/on/server',
        controller: 'Ctrl'
    });
});

Edit: to be more specific, this is the line you need somewhere:

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

like image 169
tester Avatar answered Oct 22 '22 16:10

tester