简体   繁体   English

错误未在 Postman 上显示并导致 NodeJS 服务器崩溃

[英]Error not shown on Postman and causes NodeJS server to crash

I am working on user authentication and creating a protected route using JWT. I have an authMiddleware that should throw an error if there's no token.我正在处理用户身份验证并使用 JWT 创建受保护的路由。我有一个 authMiddleware,如果没有令牌,它应该会抛出错误。 When testing this with Postman (providing no token), Postman shows使用 Postman(不提供令牌)进行测试时,Postman 显示

Could not get response
Error: read ECONNRESET 

and the server crashes.和服务器崩溃。 This is the error shown on the console:这是控制台上显示的错误:

throw new Error("Not authorized");
            ^

Error: Not authorized at protect (file:///C:/Users/Suleyman/Desktop/converter/server/middleware/authMiddleware.js:26:13)

Somehow I am getting an error on the line itself + the actual error message, but the server crashes, needing to be restarted.不知何故,我在线路本身 + 实际错误消息上收到错误,但服务器崩溃,需要重新启动。 I am using an errorMiddleware, which I don't think is the issue.我正在使用 errorMiddleware,我认为这不是问题所在。 Here's my related code:这是我的相关代码:

authMiddleware:授权中间件:


import User from '../models/userModel.js';

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

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    try {
      // Get token from header
      token = req.headers.authorization.split(" ")[1];

      // Verify token
      const decoded = jwt.verify(token, process.env.JWT_SECRET);

      // Get user from the token
      req.user = await User.findById(decoded.id).select("-password");

      next();
    } catch (error) {
      console.log(error);
      res.status(401);
      throw new Error("Not authorized");
    }
  }

  if (!token) {
    res.status(401);
    throw new Error("Not authorized, no token");
  }
}; 

controller file: controller 档案:

 // Get Me

export const getMe =  (req,res) => {
   res.json({message:'user data'})
} 

userRoutes用户路由

import { getMe, loginUser, registerUser } from "../controllers/userController.js";
import { protect } from "../middleware/authMiddleware.js";

const router = express.Router();



router.post("/register", registerUser);
router.post("/login", loginUser);
router.get("/me",protect, getMe);
 
export default router;

The problem is in your catch:问题出在你的问题上:

catch (error) {
  console.log(error);
  res.status(401);
  throw new Error("Not authorized"); // you should remove this line
}

Your catch get the error, but then you're throwing a new one which won't be catched by anyone: that's where your server is crashing.你的 catch 得到了错误,但随后你抛出了一个不会被任何人捕获的新错误:这就是你的服务器崩溃的地方。

A better way would be to pass the error to next , so it can be detected and handled in your error middleware (with your res.sendStatus(401) ):更好的方法是将错误传递给next ,这样它就可以在您的错误中间件中检测和处理(使用您的res.sendStatus(401) ):

catch (error) {
  console.error(error);
  next(error);
}

( console.error may be moved in the error middleware as well) console.error也可以在错误中间件中移动)

Your code should be the following one Because you need to send the error message in the response, So instead of throwing the error, you need to send the error using the res.status(status_code).send('error message').您的代码应该是以下代码 因为您需要在响应中发送错误消息,所以您需要使用 res.status(status_code).send('error message') 发送错误,而不是抛出错误。

import User from '../models/userModel.js';

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

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    try {
      // Get token from header
      token = req.headers.authorization.split(" ")[1];

      // Verify token
      const decoded = jwt.verify(token, process.env.JWT_SECRET);

      // Get user from the token
      req.user = await User.findById(decoded.id).select("-password");

      next();
    } catch (error) {
      console.log(error);
      // throw new Error("Not authorized");
      res.status(401).send("Not authorized");
    }
  }

  if (!token) {
    // throw new Error("Not authorized, no token");
    res.status(401).send('"Not authorized, no token"')
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM