0
votes

This maybe be seems like a total misunderstanding of a javascript way, but nevertheless here is an interest question: how to copy a XmlHttpRequest and make copy's send function include custom headers in a way that it will leave original XmlHttpRequest untouched.

Here is my (unsuccessful) attempt:

  Ajax.prototype._newReq = function() {
    var request = Object.create(XMLHttpRequest.prototype),
        token   = this.token;

    request._send = request.send;

    request.send = function(data) {
      request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      if (typeof token !== 'undefined') {
        request.setRequestHeader("X-AUTH-TOKEN", token);
      }
      this._send(data)
    }

    return request;
  }

this code throws TypeError: Illegal invocation

2
So, you're goal is to have function that returns an XMLHttpRequest that already has one or two headers already set. Why not just get a new xhr each time? For example, jsfiddle.net/zLx8orx5 - Kevin B
sure, it's totally possible and maybe is the THE way. The question above on almost 95% consists from curiosity. - lessless
I think you really shoul use new XMLHttpRequest(). Object.create will not construct an instance, and might not work. - Bergi

2 Answers

0
votes

the error was in the request.setRequestHeader("X-AUTH-TOKEN", token); after I changed it to this.setRequestHeader("X-AUTH-TOKEN", token); there were some kind of weird error and I did Kevin suggested.

0
votes

in "if (typeof token !== 'undefined')" !== is not useful because typeof always returns a string, so use !=