admin管理员组文章数量:1297131
I have a problem since yesterday and I still don't figured it out after many hours passed to try many solutions.
I'm building an app using Typescript with Express.js and I'm using nodemon server to launch the node server while coding.
Everything worked fine until I tried to implement a route which need a req.user.id (I isolated the problem and using req.user anywhere in my code make nodemon crash with the following message : "[nodemon] app crashed - waiting for file changes before starting..."
Here is details of the problematic code :
in src/controllers/profileControllers.ts
(this is a simple function for test but the error is still here) :
export const testUserProperty = async (req: Request, res: Response) => {
try {
if (!req.user || !req.user.id) {
return res.status(401).json({ error: 'Utilisateur non authentifié.' });
}
const userId = req.user.id;
const user: IUser | null = await User.findById(userId).select('-password');
if (!user) {
return res.status(404).json({ error: 'Utilisateur non trouvé.' });
}
res.status(200).json(user);
} catch (error) {
res.status(500).json({ error: 'Erreur lors de la récupération du profil.' });
}
};
with this route in src/routes/profileRoutes.ts : router.get('/profile', authenticate, testUserProperty);
and the rights imports in each files.
in my login function in src/controllers/authController.ts
I have this token generation :
const token = jwt.sign(
{ userId: user._id, email: user.email },
process.env.JWT_SECRET as string,
{ expiresIn: "1h" }
);
so there is well userId and email.
So here is my authenticate function in src/middlewares/authMiddleware.ts
:
export const authenticate = (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.header("Authorization");
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
return res.status(401).json({ message: "Accès refusé, token manquant." });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as { userId: string, email: string };
req.user = { id: decoded.userId, email: decoded.email };
if (!req.user || !req.user.id) {
return res.status(401).json({ error: 'Utilisateur non authentifié.' });
}
next();
} catch (error) {
res.status(401).json({ error: "Token invalide" });
}
};
Is there errors in this ? Everything seems to be correct for me, I have review it many times and modified things for testing, I even ask GPT 4o and even GPT o3_mini_high with every details I could share with them to help finding the error and they didn't figure it out...
This is typescript so I obviously have a types
folder with global.d.ts
in it with this content :
declare namespace Express {
export interface Request {
user?: {
id: string;
email: string;
};
}
}
and of course I have "include": ["src", "types"]
in tsconfig.json
.
I tried to use an Interface that Extends Request directly in the controller but I still had the error... nodemon invariably crash with error [nodemon] app crashed - waiting for file changes before starting...
when I use req.user.
I tried to replace every req.user
with req.body.user
just for testing and the nodemon server run perfectly so the problem is definitely linked to the use of req.user
.
So I finally post this question here, maybe someone here will help me find new avenues of research to find where this bug comes from?
Thank you very much if you help me and don't hesitate to ask me if you need more informations, or comment if you have the same problem so we can look for a solution together.
本文标签: nodejsUsing requser with JWT make my app crash with expressjs and NodemonStack Overflow
版权声明:本文标题:node.js - Using req.user with JWT make my app crash with express.js and Nodemon - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741639820a2389850.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论