dahye8043
100
2021-11-16 12:07:11 작성 2021-11-16 12:09:55 수정됨
4
227

Nextjs 웹앱 배포시 TypeError: Cannot read properties of undefined (reading 'row')


nextjs 공부하려고 레시피  공공 API를 이용하여 레시피 사이트를 만들었는데

localhost:3000에서는 에러 하나 없이 잘 동작하고 데이터도 잘뜹니다 

그런데 헤로쿠나 netlify에 배포시 빌드 과정에서 

11:48:44 AM: Unhandled error during request: TypeError: Cannot read properties of undefined (reading 'row')
11:48:44 AM: at getStaticProps (/opt/build/repo/.next/serverless/pages/recipi/[id].js:198:37)
11:48:44 AM: at processTicksAndRejections (node:internal/process/task_queues:96:5)
11:48:44 AM: at async Object.renderToHTML (/opt/build/repo/.next/serverless/chunks/403.js:18448:24)
11:48:44 AM: at async renderReqToHTML (/opt/build/repo/.next/serverless/chunks/403.js:15587:26)
11:48:44 AM: at async /opt/build/repo/node_modules/next/dist/export/worker.js:194:36
11:48:44 AM: at async Span.traceAsyncFn (/opt/build/repo/node_modules/next/dist/telemetry/trace/trace.js:60:20)
11:48:44 AM: Error occurred prerendering page "/recipi/취나물_비빔밥___청국장_쌈장". Read more: https://nextjs.org/docs/messages/prerender-error
11:48:44 AM: TypeError: Cannot read properties of undefined (reading 'row')
11:48:44 AM: at getStaticProps (/opt/build/repo/.next/serverless/pages/recipi/[id].js:198:37)
11:48:44 AM: at processTicksAndRejections (node:internal/process/task_queues:96:5)
11:48:44 AM: at async Object.renderToHTML (/opt/build/repo/.next/serverless/chunks/403.js:18448:24)
11:48:44 AM: at async renderReqToHTML (/opt/build/repo/.next/serverless/chunks/403.js:15587:26)
11:48:44 AM: at async /opt/build/repo/node_modules/next/dist/export/worker.js:194:36
11:48:44 AM: at async Span.traceAsyncFn (/opt/build/repo/node_modules/next/dist/telemetry/trace/trace.js:60:20)
11:48:44 AM: Unhandled error during request: TypeError: Cannot read properties of undefined (reading 'row')
11:48:44 AM: at getStaticProps (/opt/build/repo/.next/serverless/pages/recipi/[id].js:198:37)
11:48:44 AM: at processTicksAndRejections (node:internal/process/task_queues:96:5)
11:48:44 AM: at async Object.renderToHTML (/opt/build/repo/.next/serverless/chunks/403.js:18448:24)
11:48:44 AM: at async renderReqToHTML (/opt/build/repo/.next/serverless/chunks/403.js:15587:26)
11:48:44 AM: at async /opt/build/repo/node_modules/next/dist/export/worker.js:194:36
11:48:44 AM: at async Span.traceAsyncFn (/opt/build/repo/node_modules/next/dist/telemetry/trace/trace.js:60:20)
11:48:44 AM: Error occurred prerendering page "/recipi/오색지라시_스시". Read more: https://nextjs.org/docs/messages/prerender-error

(중략.._

이런 에러가 쭈욱 뜨네요..


폴더 구조는

이렇게 되어있고 저 파일이 문제인것 같은데

pages/recipi/[id].js의 코드는 

import axios from 'axios';
import { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import Loading from '../../components/Loading';
const Wrap = styled.div`
(중략..)
`;
const index = ({post})=>{
  const [Manual, setManual] = useState([]);
  const [ManualImg, setManualImg] = useState([]);

  useEffect(()=>{
    let arr = [...Manual];
    let imgarr = [...ManualImg];
    for(let i=1; i<=9; i++){
      let manual = "MANUAL0";
      let manualimg = "MANUAL_IMG0";
      if(post[manual+i]){
        arr.push(post[manual+i]);
      }
      if(post[manualimg+i]){
        imgarr.push(post[manualimg+i]);
      }
    };
(중략..)
  },[post]);

  return (
      <Wrap>
        <PostWrap>
          <InfoBox>
          <Left img={post.ATT_FILE_NO_MK}/>
            <Right>
              <Title>{post.RCP_NM}</Title>
              <Desc txt={"재료"}>{post.RCP_PARTS_DTLS}</Desc>
              <Desc txt={"분류"}>{post.RCP_PAT2}</Desc> 
              <Desc txt={"열량(kcal)"}>{post.INFO_ENG}</Desc>        
              <Desc txt={'영양성분'}>
                <p>탄수화물: {post.INFO_CAR}</p>
(중략..)
}

export const getStaticProps = async(context)=>{
  const {id} = await context.params;
  const name = await encodeURI(id);
  const res = await axios.get(`http://openapi.foodsafetykorea.go.kr/api/${process.env.API_KEY}/COOKRCP01/json/1/100/RCP_NM=${name}`);
  const data = await res.data;
  const post = await data.COOKRCP01.row[0];
  return {
    props: {
      post
    }
  }
}
export const getStaticPaths = async()=>{
  const res = await axios.get(`http://openapi.foodsafetykorea.go.kr/api/${process.env.API_KEY}/COOKRCP01/json/1/100`);
  const data = await res.data;
  const arr = await data.COOKRCP01.row;
  const names = await arr.map(v=>v.RCP_NM.replace(/\s/g, "_").replace(/\&/g, "_"));
  const paths = await names.map(v=>{
    return {
      params: {id: v}
    }
  })
  return {
    paths: paths,
    fallback: false,
  }
}


export default index;



이렇습니다. 저기 getStaticPagths 저 부분에서 const arr = await data.COOKRCP01.row 이 부분에서 에러 메시지에 따르면  undefined가 뜬다는데 ...

콘솔에  console.log(arr) 찍어보면 데이터 잘 나오거든요 ㅠㅠ

이렇게



그리고 로컬환경에서는 에러하나 없는데 왜 배포할때 빌드시에만 저런 에러가 계속 뜨는지 모르겠어요...

뭐가 문제일까요?ㅜㅜ

참고로 .local.env에 입력한 환경변수도 입력했고 깃허브에도 .next, node_modules는 올라가있지 않습니다 또 공공API 호출제한도 넘기지 않았습니다 ㅠㅠ


0
  • 답변 4

  • Radical Dilettante
    4
    2021-11-16 14:08:39
    옵셔널 체이닝을 한번 해보세요.
    확실히 해결될진 잘 모르겠어요
    const arr = await data?.COOKRCP01?.row
  • dahye8043
    100
    2021-11-17 01:03:30
  • 페코옹
    1k
    2021-11-17 05:54:34

    아래처럼 해주세요


    if (!router.isFallback && !pid) {

     return <ErrorPage statusCode={404} />; 

    if (router.isFallback) {

     return <div>로딩</div>

    }

  • dahye8043
    100
    2021-11-17 11:26:06

    페코옹 안돼여ㅠ저기 useEffect 전에 붙여넣으라는 말씀 맞죠ㅜㅜ

  • 로그인을 하시면 답변을 등록할 수 있습니다.