Next.js 13使用axios时出现follow-redirects模块找不到错误求助
解决Next.js 13 + Axios 中 follow-redirects 的「Module not found: Can't resolve 'debug'」错误
问题根源
该错误源于follow-redirects包依赖的debug模块缺失,或是依赖树冲突、代码逻辑错误、Next.js 13路由模式适配问题导致的。
解决方案
1. 安装缺失的debug依赖
直接安装follow-redirects所需的依赖包:
npm install debug --save # 或使用yarn yarn add debug
2. 清理缓存并重装所有依赖
若依赖树存在损坏或缓存问题,执行以下操作:
# Windows系统 rmdir /s /q node_modules del package-lock.json npm install # macOS/Linux系统 rm -rf node_modules package-lock.json npm install
3. 修复代码逻辑错误
你的getStaticProps代码存在多处问题:
- 服务器端函数中不能使用客户端状态钩子
setData/setLoading - 混合
await与then/catch导致变量作用域错误 - Axios响应已自动解析为JSON,无需再调用
response.json() - 未返回组件所需的
props
修正后的getStaticProps(仅适用于Next.js 13 Pages Router,即src/pages目录):
export async function getStaticProps() { try { const response = await axios.get('https://my-api-url.com/getlist'); const data = response.data; console.log(data); return { props: { data }, // 将数据传递给组件 }; } catch (error) { console.error('Error fetching data:', error); return { props: { data: null }, // 错误时返回默认值 }; } }
4. 适配Next.js 13 App Router(若使用src/app目录)
注意:Next.js 13的App Router不支持getStaticProps,需在Server Component中直接编写异步请求:
// src/app/page.js import axios from 'axios'; async function Home() { let data = null; try { const response = await axios.get('https://my-api-url.com/getlist'); data = response.data; console.log(data); } catch (error) { console.error('Error fetching data:', error); } return ( <div> {/* 渲染获取到的数据 */} </div> ); } export default Home;
5. 改用Next.js内置Fetch API(推荐)
避免第三方依赖的兼容问题,直接使用Next.js优化过的原生Fetch:
// Server Component或Pages Router的getStaticProps中 async function fetchData() { try { const res = await fetch('https://my-api-url.com/getlist', { cache: 'force-cache', // 对应getStaticProps的静态缓存行为 }); if (!res.ok) throw new Error('请求失败'); const data = await res.json(); return data; } catch (error) { console.error(error); return null; } }
6. 调整Axios版本
若存在版本兼容性问题,尝试安装稳定版Axios:
npm install axios@1.6.0 --save
内容的提问来源于stack exchange,提问作者Sathya
相关产品推荐
相关产品推荐

