【问题标题】:unable to set JSON object as cookie in nextjs using js-cookie无法使用 js-cookie 在 nextjs 中将 JSON 对象设置为 cookie
【发布时间】:2022-01-09 15:20:30
【问题描述】:

我正在尝试在 Cookie 中设置一些用户数据以及令牌 ID。令牌设置得很好,也在 console.log 输出中,但我的用户 JSON 对象无法设置并将“对象对象”显示为 Cookie,但我的用户数据存在于 console.log 中。我想我无法将 JSON 数据转换为 cookie。这是我用于此的 nextjs 和软件包的代码。

包使用

  1. js-cookies
  2. nextjs - 最新版本

这是我的用户登录 API

import db from "../../helpers/initDB";
import User from "../../models/User";
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'

db.connect();

// eslint-disable-next-line import/no-anonymous-default-export
export default async (req,res)=>{
 const {email,password} = req.body
 try{
    if(!email || !password){
      return res.status(422).json({error:"All Fields Are Required"})
    }
  const user = await User.findOne({email})
  if(!user){
      return res.status(404).json({error:"user dont exists with that email"})
  }
    const doMatch =  await bcrypt.compare(password,user.password)
    if(doMatch){
       const token =  jwt.sign({userId:user._id},process.env.JWT_SECRET,{
            expiresIn:"7d"
        })
        const {name,role,email} = user
        res.status(201).json({token,user:{name,role,email}})
    }else{
       return res.status(401).json({error:"email or password dont match"})
    }
 }catch(err){
     console.log(err)
 }
}

db.disconnect();

我的 api 工作正常,并使用我的所有数据设置 res.status。

这是我尝试设置 cookie 的代码部分

console.log(res2)
  Cookie.set('user', res2.user);
  Cookie.set('token', res2.token);
  router.push('/dashboard/')

这是我的 console.log 输出,其中存在用户数据和令牌

 Object { token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MWE4YzcwMGIxZmI3OWJmOGNjOWY3ZjUiLCJpYXQiOjE2Mzg1MTczODIsImV4cCI6MTYzOTEyMjE4Mn0.9T-B4c3xtsgCSGSWUMCZ_GU56FYC5VLeVDhGzAWiwjA", user: {…} }

​ 用户:对象{名称:“mohit nagar”,角色:“用户”,电子邮件:“gujjarmaxx@gmail.com”} ​​​ : 对象 { ... }

这是我的饼干

{ “请求 Cookie”:{ “标记”:“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MWE4YzcwMGIxZmI3OWJmOGNjOWY3ZjUiLCJpYXQiOjE2Mzg1MTY1NzcsImV4cCI6MTYzOTEyMTM3N30.PoBD03Qp -7- iN5yvnjvQfflTI5DO8z3Lqk3sMYZs0Y0”, “用户”:“[对象对象]” } }

我不知道我做错了什么。

【问题讨论】:

  • 你的编码/解码是否正确?

标签: json cookies next.js


【解决方案1】:

cookie 的值必须是string。你可以将stringify你的user对象转换成JSON

Cookie.set('user', JSON.stringify(res2.user))

当你想读取你的cookie时,你会解析字符串

const user = JSON.parse(Cookie.get('user'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2019-12-24
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    相关资源
    最近更新 更多