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

291
Vistas
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 Respuestas
Responde la pregunta

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 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