我正在尝试部署一个应用程序,使用Prismic作为CMS,一切都可以在本地完美地工作,但是一旦我部署到vercel,我就得到了错误:
19:09:51.850 | TypeError: Cannot read property 'titulo_categoria' of undefined当它试图从棱镜中获取数据时,似乎出现了一些问题。我的代码如下:
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,
};
}从棱镜获取数据的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;
}你知道这是怎么回事吗?我花了一整天的时间都没找到答案
发布于 2020-07-20 21:40:43
也许你已经检查过了,但既然你提到了一切都在本地工作,而不是在Vercel上,你确定你的环境变量已经在那里设置了吗?尤其是PRISMIC_API_TOKEN,因为你似乎依赖它来查询应用程序接口?
此外,我还有点担心代码的这一部分:
props: {
cat: data?.categorias ?? null,
}...where您可能会向Index组件发送一个导致错误的null值,我会尝试这样做:
props: {
cat: data?.categorias ?? {},
}...plus是否使用Index组件上的安全导航运算符(?.)?
让我知道它进行得怎么样!
https://stackoverflow.com/questions/62974450
复制相似问题