【问题标题】:Doesn Next.js API route cache the query result?Next.js API 路由是否缓存查询结果?
【发布时间】:2021-05-02 03:32:50
【问题描述】:

我有一个 Next.js 应用程序,它使用第三方 API 来显示一些数据。我正在使用 Next.js API 路由请求这些数据。这是我的/pages/api/data.js

const handler = async (req, res) => {
    const data = await fetch('https://api.example.com/v1/data');

    res.status(200).json(data);
};

export default handler;

它在幕后是如何运作的?每次我向/api/data 发送请求时,它是否会获取第三方 API?还是在构建时缓存结果?

【问题讨论】:

    标签: reactjs api next.js


    【解决方案1】:

    每次您发送请求时都会执行此操作。如果你想在构建时这样做,你必须在getStaticProps函数中获取数据:

    export async function getStaticProps(context) {
      const data = await fetch('https://api.example.com/v1/data');
    
      if (!data) {
        return {
          notFound: true,
        }
      }
    
      return {
        props: { data: res.status(200).json(data) }, // will be passed to the page component as props
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2018-04-13
      • 1970-01-01
      相关资源
      最近更新 更多