jus*_*o19 8 javascript reactjs axios next.js
试图熟悉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!" },
};
}
Run Code Online (Sandbox Code Playgroud)
我在这里想要实现的关键是在显示登录页面之前使用 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: {},
};
}
Run Code Online (Sandbox Code Playgroud)
我尝试重新启动npm run dev
仍然得到相同的结果...
因此,正如我在评论中提到的,您应该按照此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>
);
}
Run Code Online (Sandbox Code Playgroud)
当然,您需要添加消息道具。
| 归档时间: |
|
| 查看次数: |
16910 次 |
| 最近记录: |