Native XMLHttpRequest function does not underwrite passing user Token in header

I'm having trouble getting my function to underwrite the native XMLHttpRequest function so that it always passes a header containing the usuario token that is contained in my LocalStorage Currently my code looks like this:

// const oldSend = XMLHttpRequest.prototype.send
// const oldOpen = XMLHttpRequest.prototype.open

class overrideXmlHTTPRequest {
static override () {
const token = localStorage.getItem('userToken')
const xhttp = new XMLHttpRequest()
const xhrProto = XMLHttpRequest.prototype
const origOpen = xhrProto.open

xhrProto.open = function (method, url) {
  this._url = url
  return origOpen.apply(this, arguments)
}
xhttp.onreadystatechange = function () {
}
xhrProto.send = function () {
  xhrProto.setRequestHeader('UserToken', token)
}
}
}

export default overrideXmlHTTPRequest

This way when I call overrideXmlHTTPRequest.override () in my other file .vue the header remains standard and nothing has been underwritten

Author: Hugo, 2019-01-29

2 answers

Using Jquery, I believe the following solution solves your problem:

$.ajaxSetup({
  headers: {
   'TOKEN': 123
  }
});
 0
Author: user1812116, 2019-01-29 13:05:50

You can use the setRequestHeader method.

XMLHttpRequest.setRequestHeader ("UserToken", 123);

Has to make this call after the XMLHttpRequest method.open and before the XMLHttpRequest call.send

 0
Author: user1812116, 2019-01-30 14:14:48