سؤال

I have prototyped the XMLHttpRequest to add additional functionalities.
But when I try to add a custom header to the call it does not work (no errors and no calls in the chrome developer toolbar)

My code:

(function(){
var originalOpenFunction = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {

    //Add custom header
    this.setRequestHeader('custom-header', 'value');

    originalOpenFunction.call(this, method, url, async, user, pass);
};
})();

$.ajax("http://www.jsfiddle.net");

When I remove the setRequestHeader line, I get the error I expected (cross-origin not allowed).

Note Although I use jquery to test the javascript, the solution to this should be in native javascript.

JsFiddle

هل كانت مفيدة؟

المحلول

Expose errors by:

$.ajax("http://www.jsfiddle.net").fail(function (e) {
  console.log(e);
});

You will get:

InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': the object's state must be OPENED.

This means you need to call open() before you call setRequestHeader().

Then you will run into the cross domain issue. Make sure you're not trying to do a cross domain request to an unsupported domain. The shell runs from http://fiddle.jshell.net.

Requesting that domain works (returns HTML).

See: http://jsfiddle.net/HfAZN/3/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top