I am trying to create a simple registration using passsport-local
and passport-jwt
modules using the following code as my reister root/controller:
var passport = require('passport');
const User = require('../model/User');
const handleNewUser = async (req, res) => {
const { email, password } = req.body;
if (!email || !password) return res.status(400).json({ 'message': 'Username and password are required.' });
// check for duplicate usernames in the db
const duplicate = await User.findOne({ email: email }).exec();
if (duplicate) return res.sendStatus(409); //Conflict
try {
const result = User.register(new User({username : req.body.email}), req.body.password, (err , user) => {
if (err) {
res.statusCode(500);
res.setHeader('Content-Type', 'application/json');
res.json({ err: err });
} else {
console.log('success');
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, status: 'Registration Successful' });
});
}
});
console.log(result);
res.status(201).json({ 'success': `New user ${user} created!` });
} catch (err) {
res.status(500).json({ 'message': err.message });
}
}
module.exports = { handleNewUser };
And this is the error I do get:
POST /register
undefined
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
And it happens here:
res.setHeader('Content-Type', 'application/json');
I don't know why do I get this error message and how can I fix it?