繁体   English   中英

在 Next.js getServerSideProps 中,如何从浏览器获取 cookie 以识别用户

[英]In Next.js getServerSideProps, how can I fetch cookie from browser to identify the user

我正在开发一个电子商务网站。 用户已选择项目。 要查看他的购物车和结帐,他单击NavBar中的购物车图标,该图标将他导航到myCart.js页面。 我正在使用getServerSideProps从浏览器获取 JWT ,对其进行解码并验证用户。 代码如下:

let jwtoken;
export async function getServerSideProps(req, res) {

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith('Bearer')
  ) {
    jwtoken = req.headers.authorization.split(' ')[1];
  } else if (req.cookies.jwt) {
    jwtoken = req.cookies.jwt;
  }

  if (!jwtoken) {
    return res.status(423).redirect('/emptyCart');

  const decoded = await promisify(jwt.verify)(jwtoken, process.env.JWT_SECRET);

  currentUser = await User.findById(decoded.id);

  if (!currentUser) 
    return res.status(401).redirect('/signup');

注意:cookie 是 httpOnly。

我收到运行时错误: 'headers not defined'现在,如果我删除包含req.headers的代码并仅使用eq.cookies.jwt > 给我另一个错误 cookies not defined。

我在这个问题上工作了四天,并尝试了 Stackoverflow 以及其他开发人员门户(如flavioreddit等)提供的许多解决方案。

getServerSideProps function 需要一个context参数,其中包含您尝试访问的req / res对象。

尝试将您的 function 更改为具有以下签名:

export async function getServerSideProps({ req, res }) {
    // Your code here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM