NodeJS TypeError:无法读取未定义的属性(阅读“access_token”)

mv1qrgav  于 2022-12-22  发布在  Node.js
关注(0)|答案(2)|浏览(179)

TypeError:无法读取未定义的属性(正在读取"access_token")
在验证令牌(E:\电子商店\后端\实用程序\验证令牌. js:7:29)
这是验证用的虚拟令牌

const jwt = require("jsonwebtoken")
let SECRET_KEY = "90812093128309128"

const verifyToken = (req, res, next) => {
  const token = req.cookies.access_token;
  if (!token) {
    return res.status(400).send("TOKEN not found")
  }

  try {

    jwt.verify(token, SECRET_KEY, (error, user) => {
      if (error) {
        return res.status(401).send("You are not unauthorized")
      }
      req.user = user
      next()
    })

  } catch (error) {
    res.status(500).json({ status: "server error", message: error.message })

  }
}

这是来自控制器,这是控制器更新用户

const updateUser = async (req, res, next) => {
    try {
        let find = await User.findById(req.params.id)
        if (!find) {
            return req.status(400).send("User not found")
        }

        let updateUser = await User.findByIdAndUpdate(req.params.id,
            { $set: req.body },
            { new: true })
        res.status(200).json(updateUser)
    } catch (error) {
        res.status(500).json({ status: "server error", message: error.message })

    }}

这是更新路由

const express=require("express")
const router=express.Router()
const {updateUser,deleteUser,getoneUser,allUsers}=require("../controllers/users")
const {verifyToken,verifyUser,verifyAdmin}=require("../utilities/verifyToken")

router.put("/udpateuser/:id",verifyUser,updateUser )  ----> Main one

这是注册和登录控制器

const cookie = require('cookie-parser')
const express = require("express");
let SECRET_KEY = "90812093128309128"

const User = require("../models/user");
const { validationResult } = require('express-validator');
const bcryptjs = require("bcryptjs")
const jwt = require("jsonwebtoken")

const register = async (req, res, next) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  const { password, email } = User
  try {
    let user = await User.findOne({ email: email })

    if (user) {
      return res.status(409).send("Email already exists")
    }

    let salt = await bcryptjs.genSalt(10)
    let hashedPassword = await bcryptjs.hashSync(req.body.password, salt)

    newUser = await User.create({
      username: req.body.username,
      email: req.body.email,
      // password:req.body.password
      password: hashedPassword,
    })
    res.status(200).json({ status: "User is created", newUser })

  } catch (error) {
    res.status(500).json({ status: "server error", message: error.message })
  }


}

const login = async (req, res, next) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  const { password, email } = req.body

  try {
    let user = await User.findOne({ email });
    if (!user) {
      success = false
      return res.status(400).json({ error: "Please try to login with correct credentials" });
    }
    let comparePassword = await bcryptjs.compare(password, user.password)
    if (!comparePassword) {
      return res.status(400).json("incorrect login credentials")
    }

    let data = {
      user: {
        id: user.id
      }
    }
    let token = await jwt.sign({ data, isAdmin: user.isAdmin }, SECRET_KEY)
    res.cookie("access_token", token, {
      httpOnly: true
    }).status(200).json({ user, token })

  } catch (error) {
    res.status(500).json({ status: "server error", message: error.message })
  }
}
module.exports = { register, login }

这是登录和注册路径

const express=require("express");
const router = express.Router();
const { body } = require('express-validator');
const { register ,login} = require("../controllers/auth");

// REGISTRATION  ROUTE

router.post("/register",[
// username must be an email
body('username',"Username must contain at least 5 characters").isLength({ min: 5 }),
body('email',"Email is not valid").isEmail(),
// password must be at least 5 chars long
body('password',"password must contain at least 5 characters").isLength({ min: 5 }),
],register)


/// LOGIN ROUTE

router.post("/login",[

    body('email',"Email is not valid").isEmail(),
    body('password',"password must contain at least 5 characters").isLength({ min: 5 }),
 ],login)
    
module.exports=router
xqkwcwgp

xqkwcwgp1#

也许可以尝试console.log(req.cookie)来检查是否有cookie在第一时间被传递,如果有,尝试console.log(token),如果你得到一个结果,可能是你的jwt密码有问题,否则可能是你第一时间丢失了cookie。

vd2z7a6w

vd2z7a6w2#

可能是你没有安装cookie解析器。不是说这肯定是错误,但你可能

相关问题