Today I came across one issue in 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. But what if I wanted to send a pageIndex to my local API and fetch the specific page. I cant do req.body.page here, so how do I get the data ?
my API looks like this
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?
So extract the info from the pageContent then call your query.