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