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

292
Visualizações
What does this line of code in Express.JS mean: !user && res.status(401).json("Wrong credentials!"); and what does the error it creates mean?

I am following an express tutorial and came across this

router.post("/login", async (req, res) => {
  try {

    const user = await User.findOne({ username: req.body.username });                                          
    !user && res.status(401).json("Wrong credentials!");
 
    const hashedPassword = CryptoJS.AES.decrypt(user.password, process.env.PASS_SEC);
    const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
    req.body.password !== originalPassword && res.status(401).json("Wrong credentials!");
    
    const { password, ...others } = user._doc;
    res.status(200).json(others);

  } catch (err) {
    res.status(500).json(err);
  }
});

The lines i do not understand are

!user && res.status(401).json("Wrong credentials!");

I assume it is a short way of writing an if statement, however I'm not so sure. Also is this a javascript thing? a NodeJs thing? or a Express thing? never seen it before...

Also, if it is an if statement, what happens when the line is executed? Will the code "return" and not continue, or will it keep going. Because I am getting an error when intentially write the wrong username or password:

node:internal/errors:464 ErrorCaptureStackTrace(err); ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_http_outgoing:576:11) at ServerResponse.header (C:\CENSORED_NodeJS_Tutorial3\node_modules\express\lib\response.js:776:10) at ServerResponse.send (C:\CENSORED_NodeJS_Tutorial3\node_modules\express\lib\response.js:170:12) at ServerResponse.json (C:\CENSORED_NodeJS_Tutorial3\node_modules\express\lib\response.js:267:15) at C:\CENSORED_NodeJS_Tutorial3\routes\auth.js:36:21 at processTicksAndRejections (node:internal/process/task_queues:96:5) { code: 'ERR_HTTP_HEADERS_SENT' } [nodemon] app crashed - waiting for file changes before starting...

With ny beginner knowledge I am guessing it is because the code doesnt stop after hitting those lines, but I have no clue how to fix it, please help!

EDIT: here are my packages:

const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's a line of code from someone who thought they were being tricky or cute, at the (great) expense of legibility. I highly recommend against doing this sort of thing.

req.body.password !== originalPassword && res.status(401).json("Wrong credentials!");

checks whether req.body.password !== originalPassword is truthy - if it is, then it proceeds to evaluate the right-hand side:

res.status(401).json("Wrong credentials!");

A better way to write this would be:

if (req.body.password !== originalPassword) {
  res.status(401).json("Wrong credentials!");
}

It would also be good to terminate the route there, instead of proceeding on even if the credentials are wrong:

if (req.body.password !== originalPassword) {
  res.status(401).json("Wrong credentials!");
  return;
}

Will the code "return" and not continue, or will it keep going.

It will keep going - which, in this case, would not be desirable. A return should be inserted so that it doesn't keep going if the credentials are wrong.

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