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 = routerI’ve tried to put process.env.SEC_KEY in this file but it doesn’t work
Advertisement
Answer
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 🙂