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
There is no way to do this with pure javascript without using Jquery?
– Hugo
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
– user1812116