【发布时间】:2021-05-04 22:51:46
【问题描述】:
我想在网站上显示来自 YouTube 频道的最新视频。频道每天最多上传一次,所以我在vercel.json like so 中缓存了我的 API 路由响应 1 天(86400 秒):
{
"headers": [
{
"source": "/(.*)",
"headers": [
{
"key": "access-control-allow-origin",
"value": "*"
},
{
"key": "Cache-Control",
"value": "s-maxage=86400"
}
]
}
]
}
我想使用getStaticProps with incremental static regeneration,这样我的 API 路由每天最多只能收到一次发送请求,但我不确定如何将请求写入我的 API 路由。
注意:您不应使用
fetch()调用getStaticProps中的API 路由。相反,直接导入 API 路由中使用的逻辑。您可能需要针对这种方法稍微重构您的代码。从外部 API 获取很好!
这是什么意思?我现在写请求的方法有错吗?
// /pages/index.js
import Header from '../components/header/header'
import MainContent from '../components/main-content/main-content'
import Footer from '../components/footer/footer'
export default function Index({ videoTitle, videoURL, videoThumbnailData }) {
return (
<>
<Header />
<MainContent
videoTitle={videoTitle}
videoURL={videoURL}
videoThumbnailData={videoThumbnailData}
/>
<Footer />
</>
)
}
// Called at build time, and response revalidated after 1 day (86400 seconds)
// since internal API response is cached on Vercel Edge network for 1 day (see /pages/api/get-latest-video.js)
export async function getStaticProps() {
// Fetch YouTube videos from internal API route /pages/api/get-latest-video.js
const res = await fetch(`${process.env.API_ROUTES_URL}/api/get-latest-video`)
const data = await res.json()
// Returned as props to page
return {
props: {
videoTitle: data.videoTitle,
videoURL: data.videoURL,
videoThumbnailData: data.videoThumbnailData
},
revalidate: 86400
}
}
// /components/main-content/main-content.js
import Section from './section'
import Image from 'next/image'
export default function MainContent({ videoTitle, videoURL, videoThumbnailData }) {
return (
<main>
<Section>
<a href={videoURL}>
{videoTitle}
</a>
<Image
src={videoThumbnailData.url}
width={videoThumbnailData.width}
height={videoThumbnailData.height}
/>
</Section>
</main>
)
}
【问题讨论】:
-
这意味着您应该直接将逻辑导入您的
getStaticProps函数,而不是调用您的内部 API 路由。检查这个答案stackoverflow.com/questions/65752932/…,它提到了getServerSideProps,但原理是一样的。
标签: javascript reactjs api next.js vercel