在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"}
我只是想知道是否有一种"角度方式"可以覆盖$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;
}
};
});
}]);
是的,您应该能够注册一个拦截器。
只需为request
方法添加一个拦截器,并检查是否为config.method === 'POST'
,如果是,则将常量添加到发送的数据中(config.data
)。