试图熟悉 nextJS 13。
我遇到的是 getServerSideProps 函数没有预渲染页面道具。这是我第一次尝试,所以我不知道我是否做错了。
这里是/app/login/page.js
import Content from "@/components/content";
import LoginForm from "@/components/loginForm";
import Title from "@/components/title";
function Login({ message }) {
return (
<Content>
<div className="ml-2 my-2">
{message || "NextJS is ok."}
<Title text="Login" />
</div>
<LoginForm />
</Content>
);
}
export default Login;
export async function getServerSideProps() {
console.log("running getServerSideProps function..");
return {
props: { message: "NextJS is awesome!" },
};
}
我在这里想要实现的关键是在显示登录页面之前使用 axios 请求检查服务器的会话密钥。如果用户已登录,则应将用户重定向到主页。如果我能够使此功能正常工作,这是未来的代码:
export async function getServerSideProps() {
console.log("Im running getServerSideProps funct ");
let isLoggedIn = false;
try {
const response = await api.get("/users/session-check", {
withCredentials: true,
});
if (response.status === 200) isLoggedIn = true;
} catch (err) {
console.log(err.message);
}
if (isLoggedIn) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
return {
props: {},
};
}
我尝试使用 npm run dev
仍然得到相同的结果...
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您似乎正在尝试使用
getServerSideProps在显示页面之前执行服务器端渲染和身份验证检查。从您的代码来看,您似乎走在正确的轨道上。但是,我注意到您没有将从
getServerSideProps返回的 props 传递给您的Login组件。为了将服务器端属性传递给组件,您需要修改Login函数以接受message属性,如下所示:function Login({ message }) { return ( <Content> <div className="ml-2 my-2"> {message || "NextJS is ok."} <Title text="Login" /> </div> <LoginForm /> </Content> ); }此外,由于您使用的是
getServerSideProps,您的npm run dev命令不会为您的页面生成静态 HTML 文件。相反,页面将根据每个请求生成。因此,如果您想测试getServerSideProps是否正常工作,您需要向浏览器中的页面发出请求,并检查控制台日志以获取console.log( )声明。我希望这有帮助!如果您还有任何其他问题,请告诉我。
因此,正如我在评论中提到的,您应该遵循此 https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#async-and-await-in-server-components 当您使用 Next 13 和
app文件夹时。这意味着您可以尝试这样的操作:
import { redirect } from 'next/navigation'; import Content from "@/components/content"; import LoginForm from "@/components/loginForm"; import Title from "@/components/title"; async function isLoggedIn() { try { const response = await api.get("/users/session-check", { withCredentials: true, }); if (response.status === 200) return true; } catch (err) { console.log(err.message); } return false; } export default async function Page() { const isLogged = await isLoggedIn(); if (!isLogged) redirect('/'); return ( <Content> <div className="ml-2 my-2"> {"NextJS is ok."} <Title text="Login" /> </div> <LoginForm /> </Content> ); }当然,您需要添加消息道具。