I'd recommend to intercept calls to the send
method:
(function() {
var send = XMLHttpRequest.prototype.send,
token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', token);
return send.apply(this, arguments);
};
}());
This won't add the header at instantiation time, but right before the request is sent. You can intercept calls to new XMLHttpRequest()
as well, but that won't be helpful as you need to wait with adding the header until open
was called.
You might also want to include a test for the target URL of the request, so that you only add the header when your own api is called. Not doing so might leak the token elsewhere, or might even break cross-domain CORS calls that don't allow this header.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…