Nextjs - 使用 getServerSideProps 获取单个帖子数据

时间:2021-04-07 10:42:10

标签: javascript reactjs next.js fetch-api strapi

我正在使用 Nextjs + Strapi 构建一个新闻网站,因为新闻网站是高度动态的并且需要每分钟推送更新,我不能使用 getStaticProps,因为即使使用增量静态再生,这种方法也会在构建中获取数据没有任何意义,此外该网站必须具有高级搜索和用户帐户,以便他们可以个性化想要阅读的新闻类别。

我能够在布局中使用 getServerProps 来获取主菜单数据(新闻类别),我创建了动态路由但是当涉及到包含属于它的新闻文章时(单一类别),我找不到任何明确的文档。

我尝试在 ./pages/api 文件夹 getCategoryData.js 中创建一个外部方法,以使用 axioscategory.slug 作为变量从外部 api(Strapi 后端)获取单个类别数据,我能够正确获取数据,但我尝试了多种方法将类别数据分配给页面正文方法内的 const category,但没有成功并返回 undefined。

这正是我在单一类别页面中所做的: ./pages/category/[slug]/index.js

import { useRouter } from 'next/router'
import DefaultLayout from "../../../components/layouts/default";
import { getCategory } from "../../api/getCategoryData";

const CategoryArticles = ({ menuItems }) => {
    const router = useRouter()
    const { slug } = router.query

    const category  = getCategoryData(slug); 
    console.log(category) // here returns undefined !!!

    return (
        <DefaultLayout menuItems={ menuItems }>
            <div>  { category.name } </div>
        </DefaultLayout>
    );
}
export default CategoryArticles

// Note: I tried to call getCategoryData(slug) here but could not export the slug variable outside of
// page body method, also tried to use getInitialProps method for that, it did not work since I am
// using getServerSideProps. 

export async function getServerSideProps() {
    const res = await fetch('http://localhost:1337/categories')
    const data = await res.json()

    return {
        props: { menuItems: data },
    }
}

./pages/api/getCategoryData.js

import axios from "axios";

export const getCategoryData = async (slug) => {
    const response = await axios.get(`http://localhost:1337/categories?slug=${slug}`);

    console.log(response.data[0]) // here when I logged response data it returened a json object

    if (!response.data.length) {
        return {
            statusCode: 404,
        };
    }

    return {
        statusCode: 200,
        category: response.data[0],
    };

};

请问有什么建议吗?我花了 4 天在互联网上搜索,但我完全困惑了大多数教程解释了如何获取静态道具,而没有任何有关服务器端道具的详细信息, 或者我应该迁移到使用 Vue Nuxtjs,因为在那里处理这些请求更容易。

2 个答案:

答案 0 :(得分:1)

您可以从 slug 上下文访问 getServerSideProps 参数。

export async function getServerSideProps({ params }) {
    // Call external API from here directly
    const response = await axios.get(`http://localhost:1337/categories?slug=${params.slug}`);
    const data = await res.json()

    return {
        props: { menuItems: data },
    }
}

答案 1 :(得分:1)

您不能通过调用这样的方法来调用您的 api,当您尝试在客户端对其进行控制台时,api 正在您的服务器上运行。只有使用 getServerSideProps 或 nextApiRequests 等其他选项才能做到这一点。

而是直接在 getServerSideProps 内使用您的提取,它会工作得很好。

我建议您阅读此https://nextjs.org/learn/basics/api-routes/api-routes-details 更好地理解它。