无法使用 JS-cookie 在 nextjs 中将 JSON 对象设置为 cookie



我正在尝试在 Cookie 中设置一些用户数据以及令牌 ID。令牌设置完美,也在控制台.log输出中,但我的用户 JSON 对象无法设置并将"对象对象"显示为 Cookie,但我的用户数据存在于控制台.log中。我想我无法将 JSON 数据转换为 cookie。这是我用于此目的的NextJS和包的代码。

包使用

  1. js-cookie
  2. 下一页 JS - 最新版本

这是我的用户登录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/')

这是我的控制台.log存在用户数据和令牌的输出

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

用户:对象 { 名称:"Mohit Nagar",角色:"用户",电子邮件:"gujjarmaxx@gmail.com" } ​ : 对象 { ... }

这是我的饼干

{ "请求饼干":{ "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2MWE4YzcwMGIxZmI3OWJmOGNjOWY3ZjUiLCJpYXQiOjE2Mzg1MTY1NzcsImV4cCI6MTYzOTEyMTM3N30.PoBD03Qp-7-iN5yvnjvQfflTI5DO8z3Lqk3sMYZs0Y0", "用户":"[对象对象]" } }

我不知道我做错了什么。

cookie 的值必须是字符串。您可以将user对象stringify为 JSON

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

当您想读取您的cookie时,您将解析字符串

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

最新更新