简体   繁体   English

从本地 API Next.js 获取数据

[英]Fetch data from local API Next.js

Today I came across one issue in Next.js api.今天我在 Next.js api 中遇到了一个问题。 I wanted to fetch data from my internal API in getStaticProps, but as documentation says you should not fetch your local API in getStaticProps and instead you should import the function.我想在 getStaticProps 中从我的内部 API 中获取数据,但正如文档所说,您不应在 getStaticProps 中获取本地 API,而应导入该函数。 But what if I wanted to send a pageIndex to my local API and fetch the specific page.但是,如果我想将 pageIndex 发送到我的本地 API 并获取特定页面,该怎么办。 I cant do req.body.page here, so how do I get the data ?我不能在这里做 req.body.page,那么我如何获取数据?

my API looks like this我的 API 看起来像这样

export const getData = async (page) => {
    const data = await fetch(
        `https://rickandmortyapi.com/api/character?page=${page}`
    );
    const response = await data.json();
    return response;
};

export default async function getCharactersAPI(req, res) {
    //here I would like to get the data that of the page (something like req.body.page)
    //and do something like const data = await getData(req.body.page)
    const data = await getData();
    res.status(200).json(data);
}

and my fetch code looks like this我的获取代码看起来像这样

export const getStaticProps = async pageContext => {
    //here I would like to put the page I want to fetch in the getCharactersAPI()
    //and do something like const query = await getCharactersAPI(3), meaning page number 3
    const query = await getCharactersAPI();
    const response = await query.json();

    return {
        props: { response },
    };
};

The pageContext contains the URL parameters, which presumably has the page number that you want to fetch? pageContext 包含 URL 参数,大概有您想要获取的页码?

So extract the info from the pageContent then call your query.因此,从 pageContent 中提取信息,然后调用您的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM