为什么按需增量静态再生只工作时,传递一个特定的路由作为参数在Next.js?



我看过文档,来自Vercel的官方视频,有时,在重新验证API上,他们只使用斜杠调用res.unstable_revalidate('/')(可能是为了重新验证整个应用程序),有时他们调用它传递特定页面(仅重新验证该页面)。

在我的测试中,只是斜杠不工作,我不知道为什么。我如何调试这个?

下面我有一个页面,打印一个新的日期(),只有当我调用两个按钮中的一个'重新验证'或'重新验证特定'时才会更新。只"重新验证特定作品">

api/revalidate.ts

export default async function handler(req: any, res: any): Promise<any> {
// Check for secret to confirm this is a valid request
//   if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
//     return res.status(401).json({ message: 'Invalid token' });
//   }
const { page } = req.body;
if (page && !page.match(/^/.*$/)) {
return res.status(400).json({ message: 'Invalid URL' });
}
try {
if (page) {
console.info(`[Next.js] Revalidating ${page}`);
await res.unstable_revalidate(page);
} else {
console.info('[Next.js] Revalidating /');
await res.unstable_revalidate('/');
}
return res.json({ revalidated: true });
} catch (err) {
// If there was an error, Next.js will continue
// to show the last successfully generated page
return res.status(500).send('Error revalidating');
}
}

src/页面/myPage.tsx

/* eslint-disable react/button-has-type */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
export function getStaticProps() {
return {
props: {
time: new Date().toISOString(),
},
revalidate: 60,
};
}
export default function Home({ time }: { time: any }) {
function revalidate() {
fetch('api/revalidate');
}
function revalidateSpecific() {
fetch('api/revalidate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ page: '/myPage' }),
});
}
return (
<h1>
<div>{time}</div>
<div>
<button
style={{ border: '1px solid black', backgroundColor: 'transparent' }}
onClick={() => revalidate()}
>
Revalidate
</button>
</div>
<div>
<button
style={{ border: '1px solid black', backgroundColor: 'transparent' }}
onClick={() => revalidateSpecific()}
>
Revalidate specific page
</button>
</div>
</h1>
);
}

如果你的站点部署在Vercel上,你可以调用一个唯一的API URL (GET)来重建站点。https://vercel.com/docs/concepts/git/deploy-hooks creating-a-deploy-hook

相关内容

最新更新