[英]Next.js Passing props into pages,
I have the following function:我有以下 function:
export async function getServerSideProps({ req }: any) {
const user = (
await axios.get("http://localhost:4000/api/auth/status", {
withCredentials: true,
headers: { Cookie: `connect.sid=${req.cookies["connect.sid"]}` },
})
).data;
return { props: { user } };
}
Which fetches the users cookie, and then make a HTTP request using it, now I would have liked to do this in my _app.js file - however getServerSideProps() doesn't seem to be useable in there?哪个获取用户 cookie,然后使用它发出 HTTP 请求,现在我想在我的 _app.js 文件中执行此操作 - 但是 getServerSideProps() 在那里似乎不可用? Essentially, I was wondering how I would execute this function once and not have to include it in every single page file, and then be able to access its output (user) from each page.
本质上,我想知道如何执行此 function 而不必将其包含在每个页面文件中,然后能够从每个页面访问其 output(用户)。
Any suggestions would be greatly appreciated.任何建议将不胜感激。
i had same problem for use getStaticProps.我在使用 getStaticProps 时遇到了同样的问题。 my problem solved with this way.
我的问题用这种方式解决了。 you can create a
lib
folder in project root.您可以在项目根目录中创建一个
lib
文件夹。 and create getServerSide.js
file into lib
.并将
getServerSide.js
文件创建到lib
中。
export function makeServerSideProps(ns = {}) {
return async function getServerSideProps(ctx) {
return {
props: await getUserProps(ctx, ns),
};
};
}
and define function for receive user data getUserProps
.并定义 function 用于接收用户数据
getUserProps
。
export async function getUserProps(ctx, ns = ['common']) {
const user = (
await axios.get("http://localhost:4000/api/auth/status", {
withCredentials: true,
headers: { Cookie: `connect.sid=${req.cookies["connect.sid"]}` },
})
).data;
return user;
}
and use makeServerSideProps
into any pages:并在任何页面中使用
makeServerSideProps
:
import { makeServerSideProps} from 'lib/getServerSide';
import User from 'components/Authentication/User';
const UserPage = () => {
return (
<User/>
);
};
export default UserPage ;
const getServerSideProps = makeServerSideProps();
export { getServerSideProps };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.