Reputation: 571
I am using imap for user authentication to a server. I am using express for server and https://github.com/mscdex/node-imap for imap. Controller Function
exports.authenticateUser = async (req, res) => {
let username = req.body.username;
let password = req.body.password;
let imap = new Imap({
user: username,
password: password,
host: HOST_ADDRESS,
port: HOST_PORT
})
imap.once('ready', (e) => {
req.session.user = username;
return res.status(201).json({
success: true,
user: username
});
})
imap.once('error', function (err) {
console.log("err", err);
return res.status(500).json({
success: false,
error: 'Wrong credentials'
});
});
imap.connect();
}
But frequently my server stops
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Cause of some error in line
return res.status(500).json({
success: false,
error: 'Wrong credentials'
});
Upvotes: 1
Views: 455
Reputation: 11597
How about changing this
return res.status(500).json({
success: false,
error: 'Wrong credentials'
});
to This
res.status(500).send({success: false,
error: 'Wrong credentials'
});
res.status(201).send({
success: true,
user: username
});
Upvotes: 0
Reputation: 571
To resolve,
imap.once('ready', (e) => {
req.session.user = username;
imap.end()
return res.status(201).json({
success: true,
user: username
});
})
I was using IMAP for authentication, so there was no need for me to keep the connection alive, so I ended as soon as I verified the credentials. It solved the problem.
I guess what might be happening, after sending the response 201, after sometime when the connection gets terminated, on error gets triggered, resulting in again sending response, thus the error. Just a guess.
Upvotes: 1