Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading