【问题标题】:XMLHttpRequest: implementing interceptor issueXMLHttpRequest:实现拦截器问题
【发布时间】: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


    【解决方案1】:

    解决了。

    替换:

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

    适用于:

    XMLHttpRequest.prototype.open = function() { }
    

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

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 2019-04-27
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      相关资源
      最近更新 更多