简体   繁体   中英

How to import API route in NextJS for getStaticProps?

I am using NextJS's getStaticProps to fetch some data from an external API. Reading the data fetching documentation on getStaticProps I came across this particular note:

Note: You should not use fetch() to call an API route in your application. Instead, directly import the API route and call its function yourself. You may need to slightly refactor your code for this approach.

Right now I am calling getStaticProps directly from a page component called Index as follows:

export default function Index({ data }) {
  return <div>{data}</div>;
}

export async function getStaticProps() {
  const response = await fetch("http://127.0.0.1:8000/data");
  const data = await response.json();
  return { props: { data } };
}

As per the above documentation, this should not be done. How can I restructure my code to fetch data correctly? What does it mean to "import the API route and call its function yourself?"

I think that the Note is related to internal api path

You should not use fetch() to call an API route in your application

I suppose is related to every path that you define in /pages/api/* . Instead of fetch you can simply refactor your code and import data.

So, the code below is correct, don't need any refactoring

export default function Index({ data }) {
  return <div>{data}</div>;
}

export async function getStaticProps() {
  const response = await fetch("http://127.0.0.1:8000/data");
  const data = await response.json();
  return { props: { data } };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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