Harsh Patel
Harsh Patel

Reputation: 3

Cannot set headers after they are sent to the client in express

i registered successfully which inserting record in my mongodb but when i try to login error is occur on line " !user && res.status(401).json("Wrong User Name"); " that

Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:372:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (/home/hahp1908/EShopAPI/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/home/hahp1908/EShopAPI/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/home/hahp1908/EShopAPI/node_modules/express/lib/response.js:278:15)
    at /home/hahp1908/EShopAPI/routes/auth.js:42:25
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
const router = require('express').Router();
const User = require("../models/User");
const CrytoJS = require("crypto-js");

router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne(
            {
                username: req.body.user_name
            }
        );

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

        const hashedPassword = CryptoJS.AES.decrypt(
            user.password,
            process.env.PASS_SEC
        );


        const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

        const inputPassword = req.body.password;
        
        originalPassword != inputPassword && res.status(401).json("Wrong Password");
        res.status(200).json(user);
    }catch(err){
        res.status(500).json(err);
    }

});
module.exports = router

Upvotes: 0

Views: 115

Answers (1)

ParadigmShift
ParadigmShift

Reputation: 241

You need to end the execution of the function when you call res.status().json(), otherwise it will just proceed and you will again set res.status().json(). This is causing the error.

Modify to something like:

const router = require('express').Router();
const User = require("../models/User");
const CrytoJS = require("crypto-js");

router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne(
            {
                username: req.body.user_name
            }
        );

        if(!user) return res.status(401).json("Wrong User Name");

        const hashedPassword = CryptoJS.AES.decrypt(
            user.password,
            process.env.PASS_SEC
        );


        const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

        const inputPassword = req.body.password;
        
        if(originalPassword != inputPassword) return res.status(401).json("Wrong Password");
        return res.status(200).json(user);
    }catch(err){
        return res.status(500).json(err);
    }

});
module.exports = router

Upvotes: 2

Related Questions