项目部署后数据没有更新(总是得到相同的结果)

loo*_*ool 7 javascript caching reactjs next.js vercel

我在 Next.jsv13.2应用程序中创建了一个 API 端点,用于从数据库获取数据。

app/api/someData
Run Code Online (Sandbox Code Playgroud)

在我将其部署到 Vercel 上之前,它一直运行良好。我认为问题在于路由被缓存,因此每次都返回相同的响应。我该如何阻止这种情况发生?

app我正在使用Next.js 中使用Route Handlers 的新目录。

任何帮助,将不胜感激。

You*_*mar 16

这是因为在app目录和生产环境中,Next.js 默认情况下会缓存 API 路由和服务器组件中所有获取的数据。如果您使用fetch(),则可以使用revalidatecache选项更改每个查询的此行为:

fetch('https://...', { next: { revalidate: 10 } });
// OR
fetch('https://...', { cache: 'no-store' });
Run Code Online (Sandbox Code Playgroud)

如果您正在使用fetch()但想要为每个路由段设置缓存,或者您正在使用其他库(例如 )axios,或者使用 ORM 直接与数据库对话,则可以使用Route Segment Config

// layout.js OR page.js OR route.js 

import prisma from "./lib/prisma";

/*
  Bleow option is when you want no caching at all, there are more options
  on the doc depending on your needs. 
*/
export const dynamic = "force-dynamic";

async function getPosts() {
  const posts = await prisma.post.findMany();
  return posts;
}

export default async function Page() {
  const posts = await getPosts();
  // ...
}
Run Code Online (Sandbox Code Playgroud)