类型错误:无法读取未定义的属性(读取“jwt”)

问题描述 投票:0回答:1

我正在尝试使用 JWT 令牌保护我的 api 路由。我正在用邮递员测试它。令牌已成功创建并显示在邮递员中。但是当我试图保护路由时,就会出现此错误。当我尝试访问受保护的路由时会出现此错误。这是代码- 路线-

// All imports
import express from "express";

// Controllers import
import controller from "./../../../controllers/index.js";

// JWT check
import { protect } from "../../../middleware/authMiddleware.js";

// Config
const router = express.Router();

// Get all users (auth required)
router.get("/", controller.userController.getAllUsers);

// Get specific user (auth required)
router.get("/:id", controller.userController.getUserById);

// Create new user
router.post("/new", controller.userController.createUser);

// Update existing user (auth required)
router.patch("/:id/update", protect, controller.userController.updateUser);


// Delete user (auth required)
router.get("/:id/delete", protect, controller.userController.deleteUser);


// Logout the user
router.get("/:id/logout", controller.userController.logoutUser);

export default router;

中间件文件代码-

import jwt from 'jsonwebtoken';
import asyncHandler from 'express-async-handler';
import User from "../models/User.js";

const protect = asyncHandler(async (req, res, next) => {
  let token;

  token = req.cookies.jwt;

  if (token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);

      req.user = await User.findById(decoded.userId).select('-password');

      next();
    } catch (error) {
      console.error(error);
      res.status(401);
      throw new Error('Not authorized, token failed');
    }
  } else {
    res.status(401);
    throw new Error('Not authorized, no token');
  }
});

export { protect };

我几乎已经尝试了一切。软件包也是最新的。令牌在登录时创建,并在注销时删除。

javascript node.js express jwt postman
1个回答
0
投票

我遇到了同样的问题,我通过在路由中间件上方使用 cookieParser 中间件来解决

© www.soinside.com 2019 - 2024. All rights reserved.