XMLHttpRequest:实现拦截器问题

我正在尝试在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)通话出现问题...有什么想法吗?

zhongquanming 回答:XMLHttpRequest:实现拦截器问题

解决了。

已替换:

XMLHttpRequest.prototype.open = () => { }

针对:

XMLHttpRequest.prototype.open = function() { }

有关更多信息:Why do arrow functions not have the arguments array?

本文链接:https://www.f2er.com/3145506.html

大家都在问