[英]Error not shown on Postman and causes NodeJS server to crash
我正在處理用戶身份驗證並使用 JWT 創建受保護的路由。我有一個 authMiddleware,如果沒有令牌,它應該會拋出錯誤。 使用 Postman(不提供令牌)進行測試時,Postman 顯示
Could not get response
Error: read ECONNRESET
和服務器崩潰。 這是控制台上顯示的錯誤:
throw new Error("Not authorized");
^
Error: Not authorized at protect (file:///C:/Users/Suleyman/Desktop/converter/server/middleware/authMiddleware.js:26:13)
不知何故,我在線路本身 + 實際錯誤消息上收到錯誤,但服務器崩潰,需要重新啟動。 我正在使用 errorMiddleware,我認為這不是問題所在。 這是我的相關代碼:
授權中間件:
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 檔案:
// Get Me
export const getMe = (req,res) => {
res.json({message:'user data'})
}
用戶路由
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;
問題出在你的問題上:
catch (error) {
console.log(error);
res.status(401);
throw new Error("Not authorized"); // you should remove this line
}
你的 catch 得到了錯誤,但隨后你拋出了一個不會被任何人捕獲的新錯誤:這就是你的服務器崩潰的地方。
更好的方法是將錯誤傳遞給next
,這樣它就可以在您的錯誤中間件中檢測和處理(使用您的res.sendStatus(401)
):
catch (error) {
console.error(error);
next(error);
}
( console.error
也可以在錯誤中間件中移動)
您的代碼應該是以下代碼 因為您需要在響應中發送錯誤消息,所以您需要使用 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.