首页 > 解决方案 > 为什么我得到未定义的 jwt 令牌值,因为令牌存储在 cookie 中?

问题描述

服务器服务(localhost/8000)成功地将 jwt 令牌存储在 cookie 中,并将响应 cookie 发送到客户端服务。cookie 成功存储在客户端服务(localhost/3000)上,但是当我想检索它时,它显示未定义。我还包括 cookie-parser 包,但它仍然显示未定义。

服务器服务:

export const saveprofile = async (req, res) => {
    try {
        const profile = await new Profile(req.body);
        if (req.body.password === req.body.cpassword) {

            const token = await profile.generateAuthToken();
            res.cookie('token', token, { expires: new Date(Date.now() + 9999999), httpOnly: true })
            profile.save();
            res.status(200).json('profile saved !!');
        }
    } catch (error) {
        req.status(500).json(error);
    }
}

现在,当我想通过 auth 函数来控制台存储在 cookie 中的令牌时,它显示未定义。

认证功能(中间件)

import jwt from 'jsonwebtoken';
import post from '../schema/post-schema.js'
import profile from '../schema/profile-schema.js';
import Cookies from 'js-cookie';


const auth = async (req, res, next) => {
    try {
       
        const token = req.cookies.jwt;
        console.log("The token is", token) //it shows undefined

        const verifyuser = jwt.verify(token, "mynameismohitkumarfromnationalinstituteoftechnologyagartala");
        const user = await profile.findOne({ _id: verifyuser._id });
        console.log(verifyuser);
        console.log(user);
        next();
    } catch (error) {
        res.status(401).json(error);
    }
}

export default auth;

认证路由:

router.get('/post/:id', auth, getpost);

饼干图像

网络开发者工具图片

标签: javascriptnode.jsreactjsnpmcookies

解决方案


我想这里的问题是命名

"token"您在服务器服务上命名 cookie并将其保存。但是然后在 auth-middleware 中,您尝试接收"jwt"-cookie

作为旁注:

profile saved !!不是有效的 JSON


推荐阅读