getServerSideProps() 未被调用 nextJS 13

huangapple go评论81阅读模式
英文:

getServerSideProps() not being called nextJS 13

问题

Here's the translated content from your provided text:

尝试熟悉 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("I'm running getServerSideProps function");
    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 重新启动,但仍然得到相同的结果...

英文:

Was trying to get familiar with nextJS 13.
What I encountered is getServerSideProps function is not prerendering the page props. That's my first time trying it, so I don't know if I'm doing it wrong.

Here's the code written in /app/login/page.js

import Content from &quot;@/components/content&quot;;
import LoginForm from &quot;@/components/loginForm&quot;;
import Title from &quot;@/components/title&quot;;

function Login({ message }) {
	return (
		&lt;Content&gt;
			&lt;div className=&quot;ml-2 my-2&quot;&gt;
				{message || &quot;NextJS is ok.&quot;}
				&lt;Title text=&quot;Login&quot; /&gt;
			&lt;/div&gt;
			&lt;LoginForm /&gt;
		&lt;/Content&gt;
	);
}

export default Login;

export async function getServerSideProps() {
	console.log(&quot;running getServerSideProps function..&quot;);
	return {
		props: { message: &quot;NextJS is awesome!&quot; },
	};
}

Key thing I'm trying to achieve here is to check the session key with axios request to the server before displaying login page. If user's logged in, user should be redirected to homepage. Here's future code if I will be able to make this function work:

export async function getServerSideProps() {
	console.log(&quot;Im running getServerSideProps funct &quot;);
	let isLoggedIn = false;
	try {
		const response = await api.get(&quot;/users/session-check&quot;, {
			withCredentials: true,
		});
		if (response.status === 200) isLoggedIn = true;
	} catch (err) {
		console.log(err.message);
	}
	if (isLoggedIn) {
		return {
			redirect: {
				destination: &quot;/&quot;,
				permanent: false,
			},
		};
	}
	return {
		props: {},
	};
}

I tried to restart with npm run dev
Still getting the same results...

答案1

得分: 4

以下是已翻译的内容:

所以,正如我在评论中提到的,你应该遵循这个链接 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>
    );
}

当然,你需要添加你的消息属性。

英文:

So as I mentioned in a comment you should follow this https://nextjs.org/docs/app/building-your-application/data-fetching/fetching#async-and-await-in-server-components as you're using Next 13 and the app folder.

This means you can try something like this:

import { redirect } from &#39;next/navigation&#39;;
import Content from &quot;@/components/content&quot;;
import LoginForm from &quot;@/components/loginForm&quot;;
import Title from &quot;@/components/title&quot;;

async function isLoggedIn() {
    try {
        const response = await api.get(&quot;/users/session-check&quot;, {
            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(&#39;/&#39;);
    return (
        &lt;Content&gt;
            &lt;div className=&quot;ml-2 my-2&quot;&gt;
                {&quot;NextJS is ok.&quot;}
                &lt;Title text=&quot;Login&quot; /&gt;
            &lt;/div&gt;
            &lt;LoginForm /&gt;
        &lt;/Content&gt;
    );
}

Of course you need to add your message props.

答案2

得分: -3

以下是翻译好的部分:

看起来你正在尝试使用 getServerSideProps 进行服务器端渲染和在显示页面之前进行身份验证检查。从你的代码来看,似乎你走在正确的道路上。

但是,我注意到你没有将从 getServerSideProps 返回的属性传递给你的 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() 语句的输出。

希望这有所帮助!如果你有进一步的问题,请告诉我。

英文:

It looks like you're trying to use getServerSideProps to perform server-side rendering and authentication checks before the page is displayed. From your code, it seems like you're on the right track.

However, I noticed that you're not passing the props returned from getServerSideProps to your Login component. In order for the server-side props to be passed to the component, you need to modify the Login function to accept the message prop like so:

function Login({ message }) {
    return (
        &lt;Content&gt;
            &lt;div className=&quot;ml-2 my-2&quot;&gt;
                {message || &quot;NextJS is ok.&quot;}
                &lt;Title text=&quot;Login&quot; /&gt;
            &lt;/div&gt;
            &lt;LoginForm /&gt;
        &lt;/Content&gt;
    );
}

Additionally, since you're using getServerSideProps, your npm run dev command won't generate static HTML files for your pages. Instead, the pages will be generated on every request. So if you want to test if getServerSideProps is working correctly, you'll need to make a request to the page in your browser and check the console log for the output of your console.log() statement.

I hope this helps! Let me know if you have any further questions.

huangapple
  • 本文由 发表于 2023年5月18日 06:32:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定