getServerSideProps() 没有被调用 nextJS 13
P粉211600174
P粉211600174 2023-10-31 15:38:58
0
2
466

试图熟悉 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 仍然得到相同的结果...

P粉211600174
P粉211600174

全部回复(2)
P粉663883862

因此,正如我在评论中提到的,您应该遵循此 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>
    );
}

当然,您需要添加消息道具。

最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!