gpt4 book ai didi

javascript - NextJS - 在 getStaticProps 中获取动态变量

转载 作者:行者123 更新时间:2023-12-05 08:03:33 31 4
gpt4 key购买 nike

所以我有 getStaticProps 并且需要根据变量获取一些数据这里是一个例子

export async function getStaticProps() {
const res = await fetch(localWordpressUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: `
query AllPostsQuery {
posts(where: {categoryName: "blog"}) {
nodes {
slug
content
title
}
}
}
`,
})
});

const json = await res.json();
return {
props: {
posts: json.data.posts,
}
};
}

其中 categoryName: "blog"需要是一个变量而不是硬编码。我知道你可以得到鼻涕虫,但我需要的是鼻涕虫之前。即 site.com/blog/slug。对此有何建议?

最佳答案

你真的很接近。您需要的是从 getStaticProps 函数中获取上下文。将其添加到您的 getStaticProps 函数,然后查看控制台日志 以了解发生了什么。

export async function getStaticProps(context) {
console.log(JSON.stringify(context, null, 3));

const { asPath, req, res, pathname, query } = context;
if (req) {
let localWordpressURL = req.headers.host;
console.log(localWordpressURL);
}
}

关于javascript - NextJS - 在 getStaticProps 中获取动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72101692/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com