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

Nextjs + Prisma构建时出现TypeError: fetch failed错误(已解决)

Next.js /app路由构建静态页面时Prisma连接失败问题

错误信息

构建时所有调用Prisma获取数据的位置都会重复触发以下错误:

TypeError: fetch failed
    at node:internal/deps/undici/undici:12442:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async globalThis.fetch (/Users/alex/dev/wa/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:36091)
    at async i (/Users/alex/dev/wa/.next/server/app/acc/[instrument]/page.js:1:7501)
    at async g (/Users/alex/dev/wa/.next/server/app/acc/[instrument]/page.js:1:3645) {
  cause: AggregateError [ECONNREFUSED]: 
      at internalConnectMultiple (node:net:1114:18)
      at afterConnectMultiple (node:net:1667:5)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    code: 'ECONNREFUSED',
    [errors]: [ [Error], [Error] ]
}

服务端页面组件代码

export async function generateStaticParams() {
    const instruments = await getInstruments();

    return instruments.map((i) => ({
        instrument: i,
    }));
}

const Page = async ({params}) => {
     const info = await getInfo(params.instrument)
}

getInfo函数实现

const getInfo = async (instrument) => {
   const res = await fetch(`${process.env.NEXT_PUBLIC_URL}/api/instruments/${instrument}`)

if (!res.ok) { throw new Error('...') }

if(res.ok) { return await res.json() }
}

问题详情

开发环境下功能正常,但执行npx prisma generate && npx prisma migrate deploy && next build时触发上述错误。
Fetch请求能成功到达服务端GET接口,接口中Prisma调用前的console.log能正常输出,但调用const info = await prisma.info.findMany({ where: { instrument }})后的日志无显示,随后触发错误。

Prisma数据库配置

import { PrismaClient } from "@prisma/client";

const prismaClientSingleton = () => {
  return new PrismaClient();
};

type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClientSingleton | undefined;
};

const prismaClient = globalForPrisma.prisma ?? prismaClientSingleton();

export default prismaClient;

if (process.env.NODE_ENV !== "production")
  globalForPrisma.prisma = prismaClient;

NextConfig配置

/** @type {import('next').NextConfig} */
const nextConfig = {
    typescript: {
        // !! WARN !!
        // Dangerously allow production builds to successfully complete even if
        // your project has type errors.
        // !! WARN !!
        ignoreBuildErrors: true,
    },
};

module.exports = nextConfig;

版本信息

"next": "14.1.4"
"prisma": "^5.12.1",
"typescript": "5.4.4",

修复方案

无需在generateStaticParams或页面组件中调用发起API请求的getInfo函数,直接在这些服务端执行的函数中调用prisma.info.findMany即可解决问题。

疑问

原本以为构建时服务器未运行,但能输出服务端接口里Prisma调用前的console.log,这让我很困惑,到底哪里理解有误?


内容的提问来源于stack exchange,提问作者Aleksey S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:30:23