[英]Next.js Passing props into pages,
我有以下 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 } };
}
哪个获取用户 cookie,然后使用它发出 HTTP 请求,现在我想在我的 _app.js 文件中执行此操作 - 但是 getServerSideProps() 在那里似乎不可用? 本质上,我想知道如何执行此 function 而不必将其包含在每个页面文件中,然后能够从每个页面访问其 output(用户)。
任何建议将不胜感激。
我在使用 getStaticProps 时遇到了同样的问题。 我的问题用这种方式解决了。 您可以在项目根目录中创建一个lib
文件夹。 并将getServerSide.js
文件创建到lib
中。
export function makeServerSideProps(ns = {}) {
return async function getServerSideProps(ctx) {
return {
props: await getUserProps(ctx, ns),
};
};
}
并定义 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;
}
并在任何页面中使用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.