【发布时间】:2020-03-03 22:37:21
【问题描述】:
我正在尝试在 this example 之后实现一个拦截器,以便能够在发送 http 请求之前通过 monkey 修补 XMLHttpRequest#open 函数添加一个身份验证标头。
我的代码如下所示(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) 调用似乎出错了...有什么想法吗?
【问题讨论】:
标签: javascript xmlhttprequest interceptor