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

383
Vistas
Stop execution of code after returning response in Node JS?

I am new to Node JS. I am practising to build a MERN app. I have two function getUserById and isSignedIn. These two function are middlewares.

router.param("userId",getUserById)

const getUserById = (req,res,next,id)=>{
    User.findById(id).exec((err,user)=>{
        if(err){
            return res.json({
                error:"Unable to process request",
                status: false,
            })
        }
        console.log(1234);
        
        if(!user){
            return res.json({
                error:"User doesn't exist",
                status: false
            })
        }
        req.user=user;
        next()
    })
}

const isSignedIn = (req,res,next)=>{
   const token = req.headers.authorization.split(" ")[1]
   jwt.verify(token, process.env.SECRET_KEY, (err, decoded)=>{
        if(err){
            return res.json({
                status: false,
                error: "Invalid Token"
            })
        }
        console.log(123);
        req.auth=decoded
        next()
   })
};

router.post("/api/create/:userId",isSignedIn,(req,res)=>{ res.send("Success")})

This is my understanding. If in url userId is found getUserById will be executed and then isSigned in. In getUserById if there was an error or if the user doesn't exist if will send a response and the execution of code stop there. But in isSignedin if the token is not valid I am sending a response as Invalid Token and the code execution should stop there. But the code after if is also getting executed why it is so?

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

0

Try following code

router.param("userId",getUserById)

const getUserById = async (req,res,next,id)=>{

    try {
        const user = await User.findById(id)

        if(!user){
            return res.json({
                error:"User doesn't exist",
                status: false
            })
        } else {
            req.user=user;
            next()
        }

    } catch (err) {
        return res.json({
            error:"Unable to process request",
            status: false,
            error: JSON.stringify(err),
        })
    }
}

const isSignedIn = async (req,res,next)=>{
   const token = req.headers.authorization.split(" ")[1]

   try {
    const decoded = await jwt.verify(token, process.env.SECRET_KEY)
    if (decoded) {
        req.auth=decoded
        next() 
    }
   } catch (err) {
    if(err){
        return res.json({
            status: false,
            error: "Invalid Token"
        })
    }
   }
};

router.post("/api/create/:userId",isSignedIn,(req,res)=>{ res.send("Success")})
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