인프런 커뮤니티 질문&답변

강혁준님의 프로필 이미지

작성한 질문수

한 입 크기로 잘라먹는 Next.js(15+)

2.20) 배포하기

2.20) vercel에 프로젝트 배포 시 fetch failed 에러가 발생합니다

해결된 질문

24.08.25 16:53 작성

·

115

0

안녕하세요!

다름이 아니라 2.20 실습을 진행하면서 vercel에 앱을 배포하려고 하는데

Error: Command "npm run build" exited with 1

에러가 발생했습니다.

 

[cause]: Error: connect ECONNREFUSED 127.0.0.1:12345
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1607:16) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 12345
  }

vercel 에서 에러 로그를 살펴보니 book/1, book/2, book/3 페이지를 prerendering 할 때 위와 같은 에러가 발생했습니다.

로컬에서 앱을 빌드한 후 실행했을 때엔 문제가 발생하지 않았습니다 ㅠㅠ

 

export default async function fetchBookById(id: number): Promise<BookData | null> {
  const url = `http://127.0.0.1:12345/book/${id}`;
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error();
    }
    return response.json();
  } catch (error) {
    console.error(error);
    return null;
  }
}

위 코드는 book/{id}페이지로 들어왔을 때 실행하는 함수입니다!

 

import { useRouter } from "next/router";
import style from "./[id].module.css";
import fetchBookById from "@/lib/fetch-book-by-id";
import { GetStaticPropsContext, InferGetStaticPropsType } from "next";
import Head from "next/head";

export const getStaticPaths = () => {
  return {
    paths: [{ params: { id: "1" } }, { params: { id: "2" } }, { params: { id: "3" } }],
    fallback: true,
  };
};

export const getStaticProps = async (context: GetStaticPropsContext) => {
  const id = context.params!.id;

  const data = await fetchBookById(Number(id));

  return {
    props: {
      data,
    },
  };
};

export default function Page({ data }: InferGetStaticPropsType<typeof getStaticProps>) {
  const router = useRouter();

  if (router.isFallback) {
    return (
      <>
        <Head>
          <title>한입북스</title>
          <meta property="og:image" content="/thumbnail.png" />
          <meta property="og:title" content="한입북스" />
          <meta property="og:description" content="한입 북스에 등록된 도서들을 만나보세요" />
        </Head>
        <div>로딩중입니다.</div>
      </>
    );
  }

  if (!data) {
    return {
      notFound: true,
    };
  }

  const { id, title, subTitle, author, coverImgUrl, description, publisher } = data;

  return (
    <>
      <Head>
        <title>{title}</title>
        <meta property="og:image" content={coverImgUrl} />
        <meta property="og:title" content={title} />
        <meta property="og:description" content={description} />
      </Head>
      <div className={style.container}>
        <div className={style.cover_img_container} style={{ backgroundImage: `url('${coverImgUrl}')` }}>
          <img src={coverImgUrl} />
        </div>
        <div className={style.title}>{title}</div>
        <div className={style.subTitle}>{subTitle}</div>
        <div className={style.author}>
          {author} | {publisher}
        </div>
        <div className={style.description}>{description}</div>
      </div>
    </>
  );
}

혹시 몰라 해당 페이지의 전체 코드 같이 남겨봅니다 😭

감사합니다!

답변 1

0

이정환 Winterlood님의 프로필 이미지
이정환 Winterlood
지식공유자

2024. 08. 25. 17:06

안녕하세요 강혁준님 이정환입니다.

Vercel에 배포시 발생하는 해당 오류는 백엔드 서버의 배포가 이루어지지 않았기 때문에 발생하는 오류로

해당 챕터 영상의 7분 10초경 부터 오류의 원인을 설명드리고 해결하는 방법을 안내해드리고 있습니다.

해당 부분을 참고하시어 백엔드 서버를 배포한 다음 재 배포 해 보시면 될 것 같습니다.

감사합니다 😃

 

강혁준님의 프로필 이미지
강혁준
질문자

2024. 08. 25. 17:15

앗 감사합니다 이정환님 제가 제대로 영상을 확인해보지 않았었군요 ㅠㅠ

좋은 강의랑 답변 감사드립니다!