Nextjs - 使用 getServerSideProps 获取单个 post 数据

Nextjs - Fetching single post data using getServerSideProps

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

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

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

这正是我在单一类别页面中所做的: ./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 因为那里更容易处理这些请求。

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

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 },
    }
}

你不能通过调用这样的方法来调用你的 api,当你试图在客户端控制它时,api 在你的服务器上是 运行。唯一可以做到这一点的方法是使用 getServerSideProps 或其他选项,如 nextApiRequests.

而是直接在 getServerSideProps 中使用你的抓取,它会工作得很好。

我推荐你阅读这个https://nextjs.org/learn/basics/api-routes/api-routes-details 更好地理解它。