getStaticPaths 和 getStaticProps 在下一次构建期间失败

时间:2021-04-08 12:27:06

标签: javascript next.js getstaticprops getstaticpaths

我有一个带有 [slug] 用于静态站点生成的 Next.js 应用程序,一切正常,在我的本地主机上运行良好,当我尝试部署它时,显示以下错误:

“Unhandled error during request: TypeError: Cannot read property ‘title’ of undefined”.

当我尝试在本地主机上运行下一个构建命令时,显示以下错误:

Error occurred prerendering page "/jobs/[slug]". Read more: https://nextjs.org/docs/messages/prerender-error TypeError: Cannot read property 'title' of undefined

这是您的信息代码

export default function Listing({ job }) {

    const router = useRouter()

    if (!router.isFallback && !job?.slug) {
        return <ErrorPage statusCode={404} />
    }

    return (
        <div >
            <div >
                <div >
                <div >
                <div >
                <div>
                    <h1>
                    <span>Job Center</span>
                    <span >{job.title}</span>
                    <p>We are looking for interested candidates for the following position. </p>
                    </h1>
                    <div>
                            <div >
                                <span>Position: </span><span>{job.title}</span> //and multiple fields like this
                            </div>
                    </div>
                    </div>
                </div>
            </div>
        </div>
    )
    
}
 
export async function getStaticProps({ params, preview = false }) {
    const data = await getJobAndMoreJobs(params.slug, preview)
    return {
        props: {
            preview,
            job: data.job
        },
    }
}

export async function getStaticPaths() {
    const jobs = await getAllJobsWithSlug()
    return {
        paths: jobs.map(({ slug }) => ({
            params: { slug },
        })),
        fallback: true,
    }
}

此外,我还有另一个 API 文件,它从 GraphQL 架构和查询的 fetchAPI 中提取数据。下面附上代码:

async function fetchAPI(query, { variables, preview } = {}) {

    const res = await fetch(process.env.JOBS_PROJECT_API, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${
              preview
                ? process.env.JOBS_DEV_AUTH_TOKEN
                : process.env.JOBS_PROD_AUTH_TOKEN
            }`,
        },
        body: JSON.stringify({
            query,
            variables,
        }),
    })
    
    const json = await res.json()
  
    if (json.errors) {
        console.log(process.env.NEXT_EXAMPLE_CMS_GCMS_PROJECT_ID)
        console.error(json.errors)
        throw new Error('Failed to fetch API')
    }
  
    return json.data
    
}
  
export async function getPreviewPostBySlug(slug) {

    const data = await fetchAPI(
        `
        query PostBySlug($slug: String!, $stage: Stage!) {
            post(where: {slug: $slug}, stage: $stage) {
              slug
            }
        }`,
        {
            preview: true,
            variables: {
                stage: 'DRAFT',
                slug,
            },
        }
    )
    
    return data.job
    
}
  
export async function getJobAndMoreJobs(slug, preview) {

    const data = await fetchAPI(
        `
        query JobBySlug($slug: String!, $stage: Stage!) {
            job(stage: $stage, where: {slug: $slug}) {
                title
                section
                slug
                vacancies
                rank
                classification
                placeOfWork
                basicSalary
                serviceAllowance
                allowances {
                    name
                    percent
                    requirement
                }
                responsibilities
                requirement
                documents
                expirationDate
                expectedInterviewDate
                gazetteLink
                a2Form {
                    url
                }
            }
            moreJobs: jobs(orderBy: publishedAt_DESC, first: 2, where: {slug_not_in: [$slug]}) {
                title
                slug
                title
                section
                slug
                vacancies
                rank
                classification
                placeOfWork
                basicSalary
                serviceAllowance
                expirationDate
                expectedInterviewDate
                }
            }      
        `,
        {
            preview,
            variables: {
                stage: preview ? 'DRAFT' : 'PUBLISHED',
                slug,
            },
        }
    )
    
    return data
    
}

非常感谢有关此问题的任何帮助!干杯!

0 个答案:

没有答案