如何解决我在 getServerSideProps (Next.js)
我对 Next.js 和所有这些 SSR 的东西还是很陌生,所以我需要一个建议。 这是我的情况:
我在 auth 后面有一个页面,我正在尝试进行一些预取:
export const getServerSideProps: GetServerSideProps<SomeProps> = async ({ req,res }) => {
try {
const data = await fetchOnServerSide<Data[]>(someAPI,req,{
method: 'GET',});
return {
props: data,// will be passed to the page component as props
};
} catch (error) {
// Oops,you aren't authed for doing it or your token expired -> go to the "login page"
if (res) {
res.writeHead(302,{ Location: '/login' });
res.end();
}
return { props: {} };
}
};
它有效,但我想在身份验证成功后将我的其他用户从登录页面重定向回来。 在这种情况下,如何获取上一页 URL?
解决方法
您可以在重定向时将当前页面作为查询参数发送到登录页面。然后,在您的登录页面中,您可以在登录成功后重定向回该页面。
export const getServerSideProps: GetServerSideProps<SomeProps> = async ({ req }) => {
try {
const data = await fetchOnServerSide<Data[]>(someAPI,req,{ method: 'GET' });
return {
props: data
};
} catch (error) {
return {
redirect: {
destination: '/login?from=current-page',// Replace `current-page` with the actual page
statusCode: 302,}
};
}
};
我建议您从 redirect
返回 getServerSideProps
对象,而不是调用 res.writeHead
以获得更惯用的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。