本页内容

将代码从 Axios HTTP 客户端迁移到 WHATWG Fetch API;后者在 Node.js 中作为全局 fetch 原生提供,可减少依赖并提升性能。它会重写每一个 Axios 请求辅助方法——axios.request()、axios.get()、axios.delete()、axios.head()、axios.options()、axios.post()、axios.put()、axios.patch()、axios.postForm()、axios.putForm() 和 axios.patchForm()——并识别默认 ESM 导入、别名导入、CommonJS require() 调用以及动态 import()。当所有调用点都转换完成后,它还会从 package.json 中移除 axios 和 @types/axios 条目。

运行此 codemod:

普通的 axios.get() 会变成一个 fetch() 调用,并带有一个 shim,使 response.data 属性仍然可用。

-import axios from "axios";
 const base = "https://dummyjson.com/todos";

-const all = await axios.get(base);
+const all = await fetch(base)
+  .then(async (res) => Object.assign(res, { data: await res.json() }))
+  .catch(() => null);
 console.log("\nGET /todos ->", all.status);
 console.log(`Preview: ${all.data.todos.length} todos`);

axios.post() 的 data 参数会用 JSON.stringify() 序列化,并作为 body 选项传入。

-import axios from 'axios';
 const base = 'https://dummyjson.com/todos/add';

-const todoCreated = await axios.post(base, {
-  todo: 'Use DummyJSON in the project',
-  completed: false,
-  userId: 5,
-});
+const todoCreated = await fetch(base, {
+  method: "POST",
+  body: JSON.stringify({
+    todo: 'Use DummyJSON in the project',
+    completed: false,
+    userId: 5,
+  })
+})
+  .then(async (resp) => Object.assign(resp, { data: await resp.json() }))
+  .catch(() => null);
 console.log('\nPOST /todos ->', todoCreated);

axios.postForm()(以及 putForm/patchForm 变体)以 URLSearchParams 形式发送载荷。

-import axios from 'axios';
 const base = 'https://dummyjson.com/forms';

-const created = await axios.postForm(`${base}/submit`, {
-    title: 'Form Demo',
-    completed: false,
-});
+const created = await fetch(`${base}/submit`, {
+  method: "POST",
+  body: new URLSearchParams({
+      title: 'Form Demo',
+      completed: false,
+  })
+})
+  .then(async (resp) => Object.assign(resp, { data: await resp.json() }))
+  .catch(() => null);
 console.log(created);

配置对象的 url、method 和 data 属性会映射到 fetch() 调用上。

-import axios from 'axios';
-
 const base = 'https://dummyjson.com/todos/1';

-const customRequest = await axios.request({
-  url: base,
-  method: 'PATCH',
-  data: {
-    todo: 'Updated todo',
-    completed: true,
-  },
-});
+const customRequest = await fetch(base, {
+  method: "PATCH",
+  body: JSON.stringify({
+      todo: 'Updated todo',
+      completed: true,
+    })
+})
+  .then(async (resp) => Object.assign(resp, { data: await resp.json() }))
+  .catch(() => null);
 console.log('\nREQUEST /todos/1 ->', customRequest);

CommonJS 模块的处理方式相同,并且会移除不再使用的 require('axios') 绑定。

-const axios = require('axios');

 function fetchAllTodos() {
-    return axios.get('https://dummyjson.com/todos');
+    return fetch('https://dummyjson.com/todos')
+  .then(async (res) => Object.assign(res, { data: await res.json() }))
+  .catch(() => null);
 }

 module.exports = { fetchAllTodos };
  • fetch 响应通过 res.json() 而不是 data 属性暴露载荷,因此每个转换后的调用后都会跟上 .then(async (res) => Object.assign(res, { data: await res.json() })),以保持现有的 response.data 访问正常工作。
  • 转换后的调用以 .catch(() => null) 结尾,因此失败的请求会解析为 null,而不是抛出拒绝。另请注意,与 Axios 不同,fetch 在 HTTP 错误状态(4xx/5xx)下不会拒绝,因此围绕 Axios 拒绝构建的错误处理代码应手动检查。
  • 安全第一:如果文件中任何 Axios 调用使用了不受支持的配置选项,整个文件将保持不变,并打印带源码位置的警告,从而保留原有行为。
  • 转换后,codemod 会检测你的包管理器,并从 package.json 中移除 axios 和 @types/axios 依赖。

codemod 会跳过 Axios 调用使用以下任一配置选项的文件,因为这些选项没有直接对应的 fetch 等价物:

  • beforeRedirect
  • cancelToken
  • decompress
  • httpAgent
  • httpsAgent
  • maxBodyLength
  • maxContentLength
  • maxRedirects
  • paramsSerializer
  • signal
  • socketPath
  • timeout
  • transformRequest
  • transformResponse
  • validateStatus
  • withCredentials

它也不涵盖直接请求辅助方法之外的 Axios 特性,例如拦截器、取消令牌,或使用 axios.create() 创建的实例配置。