2016-03-26 39 views
2

我使用$ HTTP在AngularJS調用節點JS快遞API

var req = { 
method: 'POST', 
url: '/list', 
data: { test: 'test' } 
} 

$http(req).then(function(){ 
    console.log('then1'); 
}); 

但在節點JS(「/列表」),而我檢查它是xhr請求,返回false。

console.log('IS XHR ' + req.xhr) // IS XHR false 

我需要檢測,如果xhr請求,然後做別的事情,我怎麼能做到這一點。

回答

4

您可以添加到X-Requested-With back$httpProvider你像下面angularjs應用程序,但它已被angularjs團隊移除... https://github.com/angular/angular.js/commit/3a75b1124d062f64093a90b26630938558909e8d

象下面這樣:

var app = angular.module('yourApp', []); 

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

OR

$http.get('/list', { 
    headers: { 
    'X-Requested-With': 'XMLHttpRequest' 
    } 
}); 

您可以嘗試如下所示:

if (req.xhr || req.headers.accept.indexOf('json') > -1) { 
    //xhr response 
    } else { 

}