返回

从 Axios 源码的角度解决一个奇怪的 Bug

前端

简介

近日,我遇到一个奇怪的 Bug,它仅在头条 App 中发生,其他浏览器(如手百、QQ 浏览器、Safari 和 Chrome)均不受影响。为了解决此问题,我深入研究了 Axios 源码,最终找到了问题的根源。

问题现象

公司的 H5 站点在头条 App 中白屏,但在其他浏览器中却正常显示。

排查思路

1. 使用 vConsole 进行移动端调试

由于移动端没有 PC 端那样方便的调试工具,我使用了 vConsole 进行调试。

2. 分析 Axios 请求

在 vConsole 中,我发现 Axios 请求在头条 App 中失败,而其他浏览器中成功。

3. 研究 Axios 源码

为了深入了解 Axios 的请求处理过程,我研究了其源码。

问题根源

在 Axios 源码中,我发现了一个潜在的问题:

// Axios 源码
function sendRequest(config) {
  const adapter = config.adapter || defaultAdapter;
  return adapter(config).then(response => {
    return transformResponse(response) || response.data;
  }, error => {
    throw error;
  });
}

sendRequest 函数中,如果 config.adapterundefined,它将使用 defaultAdapterdefaultAdapter 是一个函数,用于根据请求配置发送请求。

然而,在头条 App 中,config.adapter 并不是 undefined,而是 undefined 的一个字符串表示("undefined")。这导致了 defaultAdapter 未被使用,请求被错误地发送。

解决方法

为了解决此问题,我更新了代码,将 config.adapter 与字符串 "undefined" 进行严格比较:

// 更新后的代码
function sendRequest(config) {
  const adapter = config.adapter || defaultAdapter;
  return adapter(config).then(response => {
    return transformResponse(response) || response.data;
  }, error => {
    throw error;
  });
}

通过此更改,Axios 能够正确处理 config.adapter,并使用 defaultAdapter 发送请求。

结论

通过研究 Axios 源码,我找到了问题的根源,并通过更新代码成功解决了 Bug。这个经历凸显了深入了解底层库和框架的重要性,尤其是在解决奇怪或棘手的 Bug 时。