【问题标题】:App working locally but not on production: TypeError: Cannot read property 'titulo_categoria' of undefined应用程序在本地工作但不在生产环境中:TypeError:无法读取未定义的属性“titulo_categoria”
【发布时间】:2020-11-08 11:15:03
【问题描述】:

我正在尝试使用 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;
}

知道这有什么问题吗?我一整天都在试图弄清楚,但没有任何运气

【问题讨论】:

    标签: next.js vercel prismic.io


    【解决方案1】:

    也许您已经检查过了,但是由于您提到一切都在本地工作而不是在 Vercel 上,您确定您的环境变量在那里设置吗?尤其是PRISMIC_API_TOKEN,因为您似乎依赖它来查询 API?

    另外我有点担心那部分代码:

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

    ...您可能会将 null 值发送到您的 Index 组件导致您的错误,我会尝试这样做:

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

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

    告诉我进展如何!

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 2017-09-11
      • 1970-01-01
      • 2021-03-01
      • 2020-03-28
      • 2021-10-03
      • 2018-02-16
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多