【问题标题】:In Next.js getServerSideProps, how can I fetch cookie from browser to identify the user在 Next.js getServerSideProps 中,如何从浏览器获取 cookie 以识别用户
【发布时间】:2021-04-28 21:24:44
【问题描述】:

我正在开发一个电子商务网站。用户已选择项目。要查看他的购物车和结帐,他单击 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 > 会给我另一个未定义的错误 cookie。

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

【问题讨论】:

  • 你是否在请求中传递这个中间件,即 getServerSideProps

标签: javascript node.js cookies next.js


【解决方案1】:

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

将您的 getServerSideProps 函数更改为具有以下签名:

export async function getServerSideProps({ req, res }) {
    console.log(req.cookies); // Logs all cookies from the request
}

【讨论】:

    猜你喜欢
    • 2011-02-17
    • 2016-02-23
    • 2020-12-30
    • 2015-03-07
    • 2021-12-31
    • 2012-10-28
    • 2013-05-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多