Next.js 14 App Router静态导出预渲染页面报错求助
Next.js静态导出动态路由页面报错解决及Apache部署方案
报错原因分析
预渲染/branche/[slug]/[id]/instituts页面失败,核心问题集中在构建时数据获取逻辑和缓存策略冲突:
- 静态导出阶段使用
cache: "no-store"会强制跳过缓存,导致无法预获取数据生成静态文件 - 构建环境可能无法正常访问目标API
- 缺乏错误捕获机制,单个页面数据获取失败会中断整个导出流程
代码修复步骤
1. 调整缓存策略
将getAllBranchesParams和getData中的cache: "no-store"改为cache: "force-cache"(或直接删除该配置,默认即为force-cache),确保构建时能预缓存数据:
// getAllBranchesParams 修改后 async function getAllBranchesParams() { const res = await fetch(API_URL.BRANCHE_LIST, { cache: "force-cache" }); if (!res.ok) { throw new Error("Failed to fetch branches"); } const branches: Array<BRANCHE_DATA> = await res.json().then((data) => data.branches); return branches.map((branch: BRANCHE_DATA) => ({ slug: branch.slug, id: branch.id.toString(), })); } // getData 修改后 async function getData(brancheId: number): Promise<{ branche: BRANCHE_DATA }> { const res = await fetch(`${API_URL.BRANCHE_DETAIL}/${brancheId}`, { cache: "force-cache", }); if (!res.ok) { throw new Error("Failed to fetch Instituts"); } return res.json(); }
2. 简化generateStaticParams写法
去掉冗余的链式调用,直接用await处理异步逻辑:
export async function generateStaticParams() { return await getAllBranchesParams(); }
3. 添加错误捕获机制
在页面组件中包裹数据获取逻辑,避免单个页面失败导致整个导出中断:
export default async function InstitutsPage({ params, }: { params: BranchePageParams }) { try { const data = await getData(parseInt(params.id)); return <InstitutsContainer branche={data?.branche} />; } catch (error) { console.error(`加载分支${params.id}数据失败:`, error); return <div>机构数据加载失败</div>; } }
4. 验证API可用性
执行npm run build前,确保API服务处于运行状态,且构建环境能正常访问API地址,避免因网络或服务未启动导致数据获取失败。
Apache部署步骤
1. 完成静态导出
执行npm run build,Next.js会将静态文件生成到out目录。
2. 部署静态文件
将out目录下的所有文件复制到Apache网站根目录(通常为/var/www/html)。
3. 配置Apache路由
在网站根目录创建.htaccess文件,添加以下内容确保URL正确映射到静态HTML文件:
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] # 请求的文件/目录不存在时,重定向到index.html RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
4. 启用Apache重写模块
执行以下命令启用mod_rewrite并重启Apache:
sudo a2enmod rewrite sudo systemctl restart apache2
内容的提问来源于stack exchange,提问作者Wilfried Yoro
相关产品推荐
相关产品推荐

