在Yii框架中,我们必须向POST数据添加一个CSRF令牌,以便验证请求。
令牌由PHP生成,我正在传递像这样的变量
angular.module('MyConstant', []).constant("MyConstant",
{'postdata': {'_csrf': 'ABCDEF'}}); //this is written by PHP
var app = angular.module('MyApp', ['MyConstant']);
app.controller('MyCtrl', [
'$scope', '$http', 'MyConstant',
function ($scope, $http, MyConstant) {
}]);
每当我想发送POST时,我都必须做这样的事情。
$http.post(url, angular.extend(MyConstant.postdata, {data: mydata}));
POST主体将是这样的
{"_csrf": "ABCDEF", "data": "bla bla bla"}
我很好奇是否有“Angular方式”覆盖$http.post
以自动附加数据以避免代码重复,例如上面的angular.extend(ViewConstants.postdata
。
更新
感谢@GregL指点。我可以使用interceptors
app.config(['$httpProvider', 'MyConstant',
function ($httpProvider, MyConstant) {
$httpProvider.interceptors.push(function () {
return {
request: function (config) {
if (config.method == "POST"){
config.data = angular.extend(MyConstant.postdata, config.data);
}
return config;
}
};
});
}]);
答案 0 :(得分:6)
是的,您应该可以注册interceptor。
只需为request
方法添加一个拦截器,然后检查是否config.method === 'POST'
,如果是,请将您的常量添加到发送的数据(config.data
)。