来自http://docs.angularjs.org/api/ng.$ http,它说我们应该设置默认标头以包含令牌,所以我跟着它.
我的代码就是这样的
var myapp = angular.module('myapp', ['ngCookies', 'ui.bootstrap']).
config(['$routeProvider', function($routeProvider, $httpProvider, $cookies){
$routeProvider.
when('/', {
templateUrl: '/partials/home.html',
controller: HomeCtrl
}).
when('/game/:gameId/shortlist/create',{
templateUrl: '/partials/create-shortlist.html',
controller: CreateShortlistCtrl
}).
otherwise({redirectTo: '/'});
}]);
myapp.run(function($rootScope, $http, $cookies, $httpProvider){
$http.get('/api/get-current-user').success(function(data){
$rootScope.current_user = data;
$rootScope.current_team = $rootScope.current_user.team;
});
$http.get('/api/get-current-season').success(function(data){
$rootScope.current_season = data;
});
$rootScope.csrf_token = $cookies.csrftoken;
console.log($httpProvider.defaults.headers.common);
//$httpProvider.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
});
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我已经应用了多种方法,但无法使用csrf标记设置标头.我遇到的两个错误是
未捕获错误:未知提供者:$ httpProviderProvider < - $ httpProvider
我究竟做错了什么?
我在快递中实现了csrf(跨站点请求伪造)保护,如下所示:
...
app.use(express.csrf());
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
...
Run Code Online (Sandbox Code Playgroud)
这非常有效.Angularjs在通过$ http服务发出的所有请求中使用了csrf令牌.我通过我的角度应用程序发出的请求非常好.
我的问题是测试这些api端点.我正在使用mocha运行我的自动化测试和请求模块来测试我的api端点.当我使用请求模块向使用csrf(POST,PUT,DELETE等)的端点发出请求时,即使它正确使用了cookie等,它也会失败.
还有其他人提出解决方案吗?有人需要更多信息吗?
测试示例:
function testLogin(done) {
request({
method: 'POST',
url: baseUrl + '/api/login',
json: {
email: 'myemail@email.com',
password: 'mypassword'
}
}, function (err, res, body) {
// do stuff to validate returned data
// the server spits back a 'FORBIDDEN' string,
// which obviously will not pass my validation
// criteria
done();
});
}
Run Code Online (Sandbox Code Playgroud)