[英]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); }; }());
修改本機方法對我來說看起來不合適。
我寧願創建一些助手來處理請求。
例如:
// 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() {...}
因此,您將擁有處理請求的有用幫助程序,並且您無需修改 XMLHttpRequest 原型。
我找不到檢測用於 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);
};
})();
我已經使用這個答案來覆蓋open方法。
在嚴格模式下, this.token = ...
可能會失敗。 如果這是您的情況,請使用:
let token = (arguments[0].toUpperCase() == 'POST')
? document.getElementsByTagName('meta')['csrf-token'].content
: null;
Object.defineProperty(this, 'token', token);
參考: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.