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

Next.js部署至Vercel时出现TypeError: fetch failed错误求助

问题原因

本地构建时开发服务器处于运行状态,因此你代码中通过http://localhost:3000/api/jobs发起的请求能正常响应;但Vercel的构建环境不会启动本地开发服务器,无法连接到127.0.0.1:3000,导致连接被拒绝(ECONNREFUSED),最终构建失败。

解决方案

将fetch的URL改为相对路径/api/jobs,Next.js在服务器组件/构建阶段会直接内部调用对应的Route Handler逻辑,无需发起实际HTTP网络请求,本地和Vercel部署均可正常工作。

修改后的代码:

import React from 'react'
import { Search } from '@/components'

async function getJobs() {
  // 替换为相对路径
  const res = await fetch('/api/jobs');
  if (!res.ok) {
    throw new Error("Couldn't fetch")
  }
  const data = await res.json();
  return data;
}

export default async function Home() {
  const jobs = await getJobs();

  return (
    <main className='px-6 md:px-8'>
      <Search />
      <pre>{ JSON.stringify(jobs, null, 2)}</pre>
      <span>{new Date().getTime()}</span>
    </main> 
  )
}

export const revalidate = 900;
额外优化方案

如果你的Route Handler(比如app/api/jobs/route.ts)中有独立的数据获取逻辑,可以直接导入该逻辑到页面组件,跳过fetch调用,进一步提升性能:

假设app/api/jobs/route.ts代码如下:

export async function GET() {
  const jobs = await fetchJobData();
  return Response.json(jobs);
}

// 导出独立的数据获取函数
export async function fetchJobData() {
  const res = await fetch('https://your-external-api.com/jobs');
  return res.json();
}

页面组件可直接导入使用:

import React from 'react'
import { Search } from '@/components'
import { fetchJobData } from '@/app/api/jobs/route'

async function getJobs() {
  const data = await fetchJobData();
  return data;
}

export default async function Home() {
  const jobs = await getJobs();

  return (
    <main className='px-6 md:px-8'>
      <Search />
      <pre>{ JSON.stringify(jobs, null, 2)}</pre>
      <span>{new Date().getTime()}</span>
    </main> 
  )
}

export const revalidate = 900;

内容的提问来源于stack exchange,提问作者Lindrit Sulaj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 08:17:13