Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

382
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda