xmlhttprequest native function does not overwrite by passing user token in header

Asked

Viewed 48 times

1

I’m having a hard time getting my function to overwrite the native xmlhttprequest function so that it always passes a header containing the user token that is contained in my Localstorage Currently my code is 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 another file . See The header is still default and nothing has been written

2 answers

0

Using Jquery, I believe the following solution will solve your problem:

$.ajaxSetup({
  headers: {
   'TOKEN': 123
  }
});
  • There is no way to do this with pure javascript without using Jquery?

  • 2

    You can use the setRequestHeader method. Xmlhttprequest.setRequestHeader("Usertoken", 123); You must make this call after the Xmlhttprequest.open method and before the call Xmlhttprequest.send

0

You can use the setRequestHeader method.

Xmlhttprequest.setRequestHeader("Usertoken", 123);

You must make this call after the Xmlhttprequest.open method and before the Xmlhttprequest call.send

Browser other questions tagged

You are not signed in. Login or sign up in order to post.