将代码从 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:
npx codemod @nodejs/axios-to-whatwg-fetch
普通的 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 等价物:
beforeRedirectcancelTokendecompresshttpAgenthttpsAgentmaxBodyLengthmaxContentLengthmaxRedirectsparamsSerializersignalsocketPathtimeouttransformRequesttransformResponsevalidateStatuswithCredentials
它也不涵盖直接请求辅助方法之外的 Axios 特性,例如拦截器、取消令牌,或使用 axios.create() 创建的实例配置。