$routeProvider: templateUrl requests with X-Requested-With header
Asked Answered
T

1

13

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:

Tunisia answered 20/7, 2013 at 7:55 Comment(0)
T
15

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';

Tunisia answered 20/7, 2013 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.