Reputation: 69
(function() {
var send = XMLHttpRequest.prototype.send,
token = document.getElementsByTagName('meta')['csrf-token'].content;
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', token);
return send.apply(this, arguments);
};
}());
Upvotes: 1
Views: 1231
Reputation: 1757
I couldn't find a way to detect method used for an AJAX call, but you can try:
(function() {
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
this.token = (arguments[0].toUpperCase() == 'POST')
? document.getElementsByTagName('meta')['csrf-token'].content
: null;
return proxied.apply(this, [].slice.call(arguments));
};
var send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data) {
if(this.token) {
this.setRequestHeader('X-CSRF-Token', token);
}
return send.apply(this, arguments);
};
})();
I've used this answer for overriding open method.
In strict mode, this.token = ...
could fail. If it's your case, just use:
let token = (arguments[0].toUpperCase() == 'POST')
? document.getElementsByTagName('meta')['csrf-token'].content
: null;
Object.defineProperty(this, 'token', token);
Upvotes: 2
Reputation: 352
It doesn't look right for me to modify native methods.
I'd rather create some helpers to work with requests.
For example:
// base helper that will be used for any type of requests (POST/GET/PUT/DELETE).
function makeRequest(url, settings) {
// do what ever you need here to setup a XMLHttpRequest
}
function makePostRequest(url, body) {
makeRequest(
example.com,
{
body,
headers: { 'X-CSRF-Token': token }
}
);
}
function makeGetRequest() {...}
function makePostRequest() {...}
function makeDeleteRequest() {...}
As a result you will have useful helpers to work with requests and you don't need to modify XMLHttpRequest prototype.
Upvotes: 0