![](/img/trans.png)
[英]In Next.js getServerSideProps, how can I fetch cookie from browser to identify the user
[英]How can I get cookie from browser in Next js (without use getServerSide or getInitialProps)?
我想获取位于cookies 中的authToken 。
但是当我试图得到它时,我得到了 undefined 或类似的东西。 我想使用 useContext 并将 _app 放在上下文中(以检查用户是否在子元素中获得授权),但我无法以任何方式获取 cookie。
我可以在位于 adminPanel 元素中的以下代码中获取 cookie,但我不想破坏 DRY 原则。 也许您可以向我推荐一些方法来获取身份验证的全局上下文? (没有下一个身份验证或类似的东西
export async function getServerSideProps(ctx) {
if (ctx.req) {
axios.defaults.headers.get.Cookie = ctx.req.headers.cookie
return {
props: {
cookie: ctx.req.headers.cookie ? ctx.req.headers.cookie : ''
}
}
}
我试图至少获得类似于 _app 中的授权令牌的东西,但没有任何效果(我也尝试过 getServerSideProps)。
export async function getInitialProps(ctx) {
return {
props:{
ctx
}
}
}
在这种情况下,我得到了 ctx: undefined ...
也许您可以向我推荐一些方法来获取身份验证的全局上下文? (没有下一个身份验证或类似的东西)
这个问题有很多,所以如果我不能直接回答,请原谅我,如果您需要进一步阐述,请告诉我。
首先,next 中有一个使用 cookie 的帮助包: https : //www.npmjs.com/package/next-cookies
其次,如果你想让你的getServerSideProps
保持干燥,你总是可以制作一个可重用的函数或 HOC 包装器并将其加载到任何需要它的页面中。
第三,获取 _app.jsx 的上下文与获取常规页面的上下文略有不同。 页面上下文包含在应用程序上下文中,如下所示:
import App from "next/app";
class MyApp extends App {
//...
}
MyApp.getInitialProps = async (appCtx) => {
const appProps = await App.getInitialProps(appCtx);
const { ctx } = appCtx;
console.log(ctx);
// todo: get your data from ctx here
};
但请注意,这会破坏整个站点的静态优化,因此最好将其保留在每个需要它的页面上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.