Javascript 用于$http请求的前置过滤器,如我的ajax示例
我为CSRF保护设置了一个ajax预过滤器。。这将使用MVC@Html.AntiForgeryToken()并自动将其附加到每个.ajax请求中Javascript 用于$http请求的前置过滤器,如我的ajax示例,javascript,jquery,ajax,angularjs,model-view-controller,Javascript,Jquery,Ajax,Angularjs,Model View Controller,我为CSRF保护设置了一个ajax预过滤器。。这将使用MVC@Html.AntiForgeryToken()并自动将其附加到每个.ajax请求中 $.ajaxPrefilter(function (options, originalOptions, jqXHR) { if (options.type.toUpperCase() === "POST") { // We need to add the verificationToken to all
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.type.toUpperCase() === "POST") {
// We need to add the verificationToken to all POSTs
var token = $("input[name^=__RequestVerificationToken]").first();
if (!token.length) return;
var tokenName = token.attr("name");
// If the data is JSON, then we need to put the token in the QueryString:
if (options.contentType.indexOf('application/json') === 0) {
// Add the token to the URL, because we can't add it to the JSON data:
options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
} else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
// Append to the data string:
options.data += (options.data ? "&" : "") + token.serialize();
}
}
});
现在,我需要为$http请求做同样的事情,但我真的很挣扎。有什么建议吗?我以前的一个答案中有类似的建议吗
到目前为止你试了什么?那看起来像个拦截器。查看$http文档。AngularJS是开箱即用的。无需实施您自己的拦截器查找跨站点请求伪造(XSRF)保护
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "//" + window.location.hostname + "/api/csrf", true);
xhReq.onload = function(e) {
if (xhReq.readyState === 4) {
if (xhReq.status === 200) {
app.constant("CSRF_TOKEN", xhReq.responseText);
app.run(['$http', 'CSRF_TOKEN', function($http, CSRF_TOKEN) {
$http.defaults.headers.common['X-Csrf-Token'] = CSRF_TOKEN;
}]);
}
}
};
xhReq.send(null);