【问题标题】:Why am i getting undefined jwt token value since token is stored in cookies?为什么我得到未定义的 jwt 令牌值,因为令牌存储在 cookie 中?
【发布时间】:2021-11-03 11:42:43
【问题描述】:

服务器服务(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);

【问题讨论】:

  • 为什么要使用 res.cookie 和 req.cookies.jwt?你好像在使用 js-cookie,也就是说你应该使用 Cookies.set 和 Cookies.get。
  • 你试过控制台记录父对象吗? req.cookies 或者只有 req 对象。
  • 是的,我试图控制 req.cookies 它显示为 [Object: null prototype] {}。
  • 实际上在网络(开发者工具)中显示状态码为 401 Unauthorized on routing '/post/:id'。

标签: javascript node.js reactjs npm cookies


【解决方案1】:

我猜这里的问题是命名

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

附注:

profile saved !! 不是有效的 JSON

【讨论】:

  • 是的,这是一个拼写错误。我使它正确,但仍然显示未定义。实际上在网络(开发人员工具)中,它显示状态代码为 401 Unauthorized
猜你喜欢
  • 2022-08-10
  • 2022-01-15
  • 2015-09-15
  • 2016-09-13
  • 2021-10-16
  • 2017-12-13
  • 2020-07-24
  • 2019-02-01
  • 2016-05-03
相关资源
最近更新 更多