[英]Modify headers of only POST XMLHttpRequest
(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); }; }());
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.因此,您将拥有处理请求的有用帮助程序,并且您无需修改 XMLHttpRequest 原型。
I couldn't find a way to detect method used for an AJAX call, but you can try:我找不到检测用于 AJAX 调用的方法的方法,但您可以尝试:
(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.我已经使用这个答案来覆盖open方法。
In strict mode , this.token = ...
could fail.在严格模式下,
this.token = ...
可能会失败。 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);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty参考: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.