应用程序在本地运行但不在生产环境中运行:TypeError:无法读取未定义的属性“ titulo_categoria”

时间:2020-07-18 22:34:12

标签: next.js vercel prismic.io

我正在尝试使用Prismic作为CMS部署应用程序,并且一切都在本地正常运行,但是一旦部署到Vercel,我会收到错误消息:

19:09:51.850 | TypeError: Cannot read property 'titulo_categoria' of undefined

当它试图从Prismic获取数据时似乎出了点问题。 我的代码如下:

import {getAllCategorias, getCategory2} from '../../lib/api';

export default function Index({cat}) {
  return <>{cat.titulo_categoria[0].text}</>;
}

export async function getStaticProps({params}) {
  const data = await getCategory2(params.slug);
  return {
    props: {
      cat: data?.categorias ?? null,
    },
  };
}

export async function getStaticPaths() {
  const allPosts = await getAllCategorias();
  return {
    paths: allPosts?.map(({node}) => `/test/${node._meta.uid}`) || [],
    fallback: true,
  };
}

从Prismic获取数据的API代码是:

import Prismic from 'prismic-javascript';

const REPOSITORY = process.env.PRISMIC_REPOSITORY_NAME;
const REF_API_URL = `https://${REPOSITORY}.prismic.io/api/v2`;
const GRAPHQL_API_URL = `https://${REPOSITORY}.prismic.io/graphql`;
// export const API_URL = 'https://your-repo-name.cdn.prismic.io/api/v2'
export const API_TOKEN = process.env.PRISMIC_API_TOKEN;
export const API_LOCALE = process.env.PRISMIC_REPOSITORY_LOCALE;

export const PrismicClient = Prismic.client(REF_API_URL, {
  accessToken: API_TOKEN,
});

async function fetchAPI(query, {previewData, variables} = {}) {
  const prismicAPI = await PrismicClient.getApi();
  const res = await fetch(
    `${GRAPHQL_API_URL}?query=${query}&variables=${JSON.stringify(variables)}`,
    {
      headers: {
        'Prismic-Ref': previewData?.ref || prismicAPI.masterRef.ref,
        'Content-Type': 'application/json',
        'Accept-Language': API_LOCALE,
        Authorization: `Token ${API_TOKEN}`,
      },
    }
  );

  if (res.status !== 200) {
    console.log(await res.text());
    throw new Error('Failed to fetch API');
  }

  const json = await res.json();
  if (json.errors) {
    console.error(json.errors);
    throw new Error('Failed to fetch API');
  }
  return json.data;
}

export async function getCategory2(slug) {
  const data = await fetchAPI(
    `
  query CategoryBySlug($slug: String!, $lang: String!) {
    categorias(uid: $slug, lang: $lang) {
      titulo_categoria
      _meta {
        uid
      }
    } 
  }
  `,
    {
      variables: {
        slug,
        lang: API_LOCALE,
      },
    }
  );

  return data;
}

有什么想法吗?我一直想整天都没有运气

1 个答案:

答案 0 :(得分:0)

也许您已经检查过了,但是由于您提到了所有内容都在本地运行,而不是在Vercel上运行,因此您确定在此处设置了环境变量吗?尤其是PRISMIC_API_TOKEN,因为它似乎是您依靠它来查询API?

我也担心那部分代码:

props: {
  cat: data?.categorias ?? null,
}

...您可能会向您的null组件发送一个Index值,从而导致您的错误,我会尝试这样做:

props: {
  cat: data?.categorias ?? {},
}

...加上在?.组件上使用安全导航运算符(Index)了?

让我知道怎么回事!