Así que tengo algo como esto en uno de mis controladores:
module.exports.authToken = (req, res, next) => { const token = req.cookies.jwt; //console.log(token); if (!token) { return res.sendStatus(403); } try { const data = jwt.verify(token, "secret token"); console.log(data); req.userId = data.id; return next(); } catch { return res.sendStatus(403); } };y es llamado por una ruta:
router.get("/protected", authController.authToken, (req, res) => { return res.json({ user: { id: req.userId, role: req.userRole } }); });y quiero obtener una respuesta JSON de esa ruta en uno de mis otros controladores. Intenté algunas cosas pero ninguna funcionó.
Lo que haría sería abstraer la respuesta a una función para su reutilización:
// the function will just return the data without writing it to the response function protectedRoute(req) { return {user: {id: req.userId, role: req.userRole}}; } router.get("/protected", authController.authToken, (req, res) => { // in the actual handler you can return the response return res.json(protectedRoute(req)); }); // make sure the middleware is still being run router.get("/other_route", authController.authToken, (req, res) => { // use the same function to get the response from /protected const protectedResponse = protectedRoute(req); // do stuff with it });