Home > Software engineering >  Cannot set headers after they are sent to the client error nodejs error
Cannot set headers after they are sent to the client error nodejs error

Time:01-24

When I am trying to post login data in Postman I get an error Cannot set headers after they are sent to the client.

const router = require('express').Router();
const User = require('../models/user');
const Crypto = require('crypto-js');
const { response } = require('express');
const secretKey = process.env.SECRET_KEY;
//  Create a registration

router.post('/rejestracja', async (req, res)=>{
    const nowyUser = new User({
        email: req.body.email,
        password: Crypto.AES.encrypt(req.body.password, process.env.SEC_KEY).toString(),
        firstName: req.body.firstName,
        surname: req.body.surname,
        username: req.body.username,
    });
    try{
        const newedUser = await nowyUser.save();
        res.status(201).json(newedUser);
    }
    catch(err){res.status(500).json(err)};
})
 
// Create a login

router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne({email: req.body.email});
        !user && res.status(401).json("i/lub hasło jest nieprawidłowy");
        

        const securedPass = Crypto.AES.decrypt( user.password, process.env.SECRET_KEY);
        const password = securedPass.toString(Crypto.enc.Utf8);
        
        password !== req.body.password && res.status(401).json("Email i/lub hasło jest nieprawidłowy");
        
        response.status(200).json(user);
        console.log("dziala");
    } 
    catch(err) {
        res.status(500).json({message: err.message});
    }
    
});


module.exports = router

Error Scr

I've tried to put process.env.SEC_KEY in this file but it doesn't work

CodePudding user response:

It seems that you're trying to send response twice:

password !== req.body.password && res.status(401).json("Email i/lub hasło jest nieprawidłowy");
    
response.status(200).json(user);

Also you're using response imported form the express. I'm not sure why you need it, but you probably should use the existing res instead.

All in all, I believe that the solution you're looking for is this:

if (password !== req.body.password) {
  res.status(401).json("Email i/lub hasło jest nieprawidłowy");
} else {
  res.status(200).json(user);
}

Good luck :)

CodePudding user response:

I believe you want to break out of your code flow whenever you perform a res.status(x). In cases such as this:

!user && res.status(401).json("i/lub hasło jest nieprawidłowy");

You'll set the status and the JSON of the response, but the code will continue, so you'll eventually get to setting the status again (either to 401 if the password isn't there, or 200 if it is).

Try something like this instead:

if (!user) {
  return res.status(401).json("i/lub hasło jest nieprawidłowy");
}

(Same thing for the password check.)

  • Related