我正在尝试在this example之后实现拦截器,以便能够通过 monkey patching XMLHttpRequest#open
函数发送http请求之前添加身份验证标头。
我的代码如下所示(storage
只是一个保存访问令牌的服务):
// 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
});
});
但是当调用.open()
时,出现以下错误:
InvalidStateError:对象处于无效状态。
3 |
4 | XMLHttpRequest.prototype.open = () => {
> 5 | const res = oldXHROpen.apply(this,arguments);
| ^
6 |
7 | const accessToken = storage.get();
8 |
似乎oldXHROpen.apply(this,arguments)
通话出现问题...有什么想法吗?