Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
Can i use route inside a controller in express js?

So I have something like this in one of my controllers:

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);
      }
  };

and it's called by a route:

router.get("/protected", authController.authToken, (req, res) => {
    return res.json({ user: { id: req.userId, role: req.userRole } });
  });

and I want to get a JSON response of that route in one of my other controllers. I tried some things but none of it worked.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

What I would do is abstract the response out to a function for re-use:

// 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
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda