您还可以在 getServerSideProps 和 API Routes 中使用缓存标头来进行动态响应。例如,使用 stale-while-revalidate。
如果您使用 Vercel 来托管您的前端,只需一行代码,您就可以利用 stale-while-revalidate 缓存策略,该策略在使用重新验证时与 getStaticProps 的行为非常相似。
// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props: {},
}
}
查看文档:https://nextjs.org/docs/going-to-production#caching
但重要的是要知道何时在 next.js 中使用 getServerSideProps 或 api url
何时使用getServerSideProps
每次用户请求页面时,getServerSideProps 函数都会获取数据。它会在将页面发送给客户端之前获取数据。如果客户端发出后续请求,则会再次获取数据。在这些情况下,使用:
- SEO 对页面很重要
- 获取的内容很重要且更新频繁
- 当我们想要获取与用户的 cookie/活动相关的数据并且因此无法缓存时。具有用户身份验证功能的网站最终会大量依赖 getServerSideProps 来确保用户在完成请求之前正确登录。
如果页面不是 SEO 关键,例如,如果您需要为管理员获取当前用户,则不需要使用 getServerSideProps。但是,如果您要为主页获取购物项目,最好使用getServerSideProps。
什么时候使用api函数
重要的是要了解,我们正在构建的某些网站不仅需要根据请求将 Html 页面返回给用户。例如,您的网站上可能有一项功能,允许用户提交反馈或注册时事通讯。因此,当用户单击此类按钮以注册时事通讯时,请考虑在我们注册时事通讯时幕后发生的情况。
我们需要将数据发送到某个服务器以存储在某个数据库中输入的时事通讯电子邮件地址,并且发送的请求不是获取站点,而是存储数据。我们不想获得一个 Html 页面,而是希望将该用户输入的数据发送到某个数据库。这就是我们使用 API 的原因。有不同类型的 api,但主要思想是相同的。我们有一个服务器,它公开了一些特定的 url。这些 url 不仅仅是发送 html 数据,而是接受一些数据并用任何类型的数据发送回响应。
所以 Api 路由是一种特殊的 Url,您可以将其添加到 next.js 应用程序中,它不是关于获取标准浏览器请求并发送回预呈现的 html 页面,而是关于获取数据,可能使用数据将数据存储在某个数据库中,并以您选择的任何形式发回数据。