You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS 14构建预渲染页面报错:fetch失败(ECONNREFUSED)

NextJS 14 构建时预渲染页面出现 ECONNREFUSED 错误的解决方案

问题核心

开发环境npm run dev运行正常,但执行npm run build时,/admin/checklist页面预渲染阶段触发fetch请求失败,错误码ECONNREFUSED;其他使用相同getCategories()函数的页面无此问题,删除该页面后构建成功。

原因分析

  • 构建阶段的静态预渲染在Node.js环境中执行,若process.env.API_URL指向本地开发服务器(如http://localhost:3000),而此时开发服务器并未运行,就会触发连接拒绝错误。
  • 其他页面可能因路由特性、渲染模式配置(如动态路由、dynamic: 'force-dynamic'),未被静态预渲染,而是在用户访问时才发起请求,因此不会触发该问题。

解决方法

方案1:强制页面动态渲染

在AdminChecklist页面组件中添加动态渲染配置,让页面跳过构建时的预渲染,仅在用户访问时执行数据请求:

export const dynamic = 'force-dynamic'

import React from 'react'
import { jsonHeaders } from '@/lib/const'

async function getCategories() {
  const res = await fetch(`${process.env.API_URL}/api/user/category`, 
                            { 
                              headers: jsonHeaders,
                            })
  if (!res.ok) {
    throw new Error('Failed to fetch data')
  }
  return res.json()
}

const AdminChecklist = async () => {
  const data = await getCategories()
  
  return (
    <div>AdminChecklist</div>
  )
}

export default AdminChecklist

方案2:构建前启动API服务

若需要静态预渲染该页面,需在执行npm run build前启动对应的API服务(如后台业务服务),确保process.env.API_URL指向的地址在构建时可正常访问。

方案3:直接调用业务逻辑替代fetch请求

如果API属于同项目的后端逻辑,可跳过HTTP请求,直接在getCategories中调用数据层代码:

import React from 'react'
// 假设数据层逻辑文件路径
import { getCategoriesFromDB } from '@/lib/categories'

async function getCategories() {
  // 直接调用数据库查询或业务逻辑,而非fetch请求
  const data = await getCategoriesFromDB()
  return data
}

const AdminChecklist = async () => {
  const data = await getCategories()
  
  return (
    <div>AdminChecklist</div>
  )
}

export default AdminChecklist

方案4:配置构建环境的API地址

在.env.production文件中设置构建时可用的API地址(如测试环境API),替换本地开发地址:

# .env.production
API_URL=https://your-test-api-domain.com

内容的提问来源于stack exchange,提问作者Arif Oyong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:20:24