Reputation: 6127
I am trying to implement an interceptor following this example to be able to add an authentication header before sending an http request by monkey patching the XMLHttpRequest#open
function.
My code is shown below (storage
is just a service that holds the access token):
// auth-interceptor.js
module.exports = ({ storage }) => {
const oldXHROpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = () => {
const res = oldXHROpen.apply(this, arguments);
const accessToken = storage.get();
if (accessToken) {
this.setRequestHeader('Authentication', accessToken);
}
return res;
};
};
// auth-interceptor.spec.js
describe('auth interceptor', () => {
let fakeTokenStorage;
beforeEach(() => {
fakeTokenStorage = { get: () => 'xxxx-access-token-xxxx' };
authInterceptor({ storage: fakeTokenStorage });
});
it('should include authentication header', () => {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://base_url/api/check');
// check if header exists
});
});
But when .open()
gets called I get the following error:
InvalidStateError: The object is in an invalid state.
3 |
4 | XMLHttpRequest.prototype.open = () => {
> 5 | const res = oldXHROpen.apply(this, arguments);
| ^
6 |
7 | const accessToken = storage.get();
8 |
It seems that the oldXHROpen.apply(this, arguments)
call is going wrong... any ideas?
Upvotes: 1
Views: 817
Reputation: 6127
Got it solved.
Replaced:
XMLHttpRequest.prototype.open = () => { }
For:
XMLHttpRequest.prototype.open = function() { }
For further information: Why do arrow functions not have the arguments array?
Upvotes: 1