TypeError:fetch failed during Next.js project build

yshpjwxd  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(140)

我在部署Vercel时遇到了这个错误:

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11457:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED 127.0.0.1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 3000
  }
}
Error occurred prerendering page "/match". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11457:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

字符串
我想可能是因为http://localhost:3000/api/event,我如何才能更换一个正确的网址到localhost

async function getData(): Promise<Events[]> {
  const data = await fetch(`http://localhost:3000/api/event`, {
    cache: "no-cache",
  }).then((res) => res.json());
  return data;
}

m528fe3b

m528fe3b1#

如果您在构建时尝试从服务器组件调用内部API路由,则会发生此错误,其中没有应用程序正在运行(应用程序正在构建且尚未部署)。来自Next.js的Tim Neutkens在GitHub问题上指出了类似的错误:
这是因为您在构建期间尝试从内部API路由获取,这是不支持的。
不要从服务器组件调用内部API路由,然后调用您的数据库或CMS,而是直接从组件到达它们。这有助于避免错误,以及额外的无用API调用。
已经说过,如果API不是您的内部API,您可以替换

fetch('http://localhost:3000/api/event')

字符串

fetch(process.env.URL + '/api/even')


然后创建一个.env文件,在其中添加:

URL=http://localhost:3000


然后在Vercel Jmeter 板上,使用生产URL设置URL环境变量。

kt06eoxx

kt06eoxx2#

发生此错误的原因可能是在部署到Vercel时在代码中使用了http://localhost:3000/api/event URL。当应用程序处于部署模式时,localhost地址不再引用您自己的系统,您应该使用API所在的实际服务器地址。
要解决此问题,最好使用环境变量来确定API地址。在开发和测试环境中,您可以使用http://localhost:3000,但在部署到Vercel时,您应该使用Vercel服务器的地址来访问API。
例如,您可以在Vercel中使用环境变量。首先,在Vercel设置中定义环境变量。创建一个名为NEXT_PUBLIC_API_URL的环境变量,并将其值设置为您的API地址(例如,https://your-api-domain.com)。
然后,在代码中,使用NEXT_PUBLIC_API_URL环境变量进行API通信:

async function getData(): Promise<Events[]> {
  const apiUrl = process.env.NEXT_PUBLIC_API_URL; // Using an environment variable
  const data = await fetch(`${apiUrl}/api/event`, {
    cache: "no-cache",
  }).then((res) => res.json());
  return data;
}

字符串
通过这些更改,您的应用程序应该能够在所有环境(开发、测试、部署)中正确地与API通信,并且应该解决EASP.REFUSED错误。

1qczuiv0

1qczuiv03#

这个问题可以通过用127.0.0.1替换localhost来解决。
更多细节可以在相关的GitHub discussion中找到。

相关问题