When I am trying to post login data in Postman I get an error Cannot set headers after they are sent to the client.
JavaScript
x
46
46
1
const router = require('express').Router();
2
const User = require('../models/user');
3
const Crypto = require('crypto-js');
4
const { response } = require('express');
5
const secretKey = process.env.SECRET_KEY;
6
// Create a registration
7
8
router.post('/rejestracja', async (req, res)=>{
9
const nowyUser = new User({
10
email: req.body.email,
11
password: Crypto.AES.encrypt(req.body.password, process.env.SEC_KEY).toString(),
12
firstName: req.body.firstName,
13
surname: req.body.surname,
14
username: req.body.username,
15
});
16
try{
17
const newedUser = await nowyUser.save();
18
res.status(201).json(newedUser);
19
}
20
catch(err){res.status(500).json(err)};
21
})
22
23
// Create a login
24
25
router.post('/login', async (req, res) => {
26
try{
27
const user = await User.findOne({email: req.body.email});
28
!user && res.status(401).json("i/lub hasło jest nieprawidłowy");
29
30
31
const securedPass = Crypto.AES.decrypt( user.password, process.env.SECRET_KEY);
32
const password = securedPass.toString(Crypto.enc.Utf8);
33
34
password !== req.body.password && res.status(401).json("Email i/lub hasło jest nieprawidłowy");
35
36
response.status(200).json(user);
37
console.log("dziala");
38
}
39
catch(err) {
40
res.status(500).json({message: err.message});
41
}
42
43
});
44
45
46
module.exports = router
I’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:
JavaScript
1
4
1
password !== req.body.password && res.status(401).json("Email i/lub hasło jest nieprawidłowy");
2
3
response.status(200).json(user);
4
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:
JavaScript
1
6
1
if (password !== req.body.password) {
2
res.status(401).json("Email i/lub hasło jest nieprawidłowy");
3
} else {
4
res.status(200).json(user);
5
}
6
Good luck 🙂