javascriptnode.jsexpresshttp-headers

"Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" when trying to detect duplicates in my database


I have a backend written using express.js which does the standard CRUD ops. I am using sequelizer as my ORM.

Here's the code:

import { Sequelize} from 'sequelize';
import User from '../Models/User.js';
import bcrypt from 'bcrypt';
async function getUserByUsername(username) {

try {
    // Find a user record with the specified username
    const foundUser = await User.findOne({
        where: {
            username: username
        }
    });

    // Check if the user was found
    if (foundUser) {
        return true;
    } else {
        false;
    }
} catch (error) {
    console.error('Error finding user:', error);
}
   }

 const sequelizer = new Sequelize.Sequelize({
    dialect: 'sqlite',
    storage: 'DergiKullanicilar.db'
  });

const createUser = async (req,res)=>{
const data = req.body ?? {};

const user = {username : data.username, email:data.email, password:data.password,role:data.role ?? 'user'};

if (!user.username || !user.password)
{
    res.status(400).json({'message': 'username and password are required'})
    return;
}

// check for duplicates
if (await getUserByUsername(user.username))
{
    res.sendStatus(409).json({"message":"user already exists"});
    return;
}

const salt = await bcrypt.genSalt(10);

user.password = await bcrypt.hash(user.password,salt);
try {
    // Create a new user record with the provided data
    const newUser = await User.create(user);

    // Return the newly created user record
    res.sendStatus(201);
    return
  } catch (error) {
    res.sendStatus(500);
    // Handle any errors that occur during the insert operation
    console.error('Error creating user:', error);
    throw error; // Rethrow the error to be handled by the caller
  }
}

export default {createUser};

The issue arises at the getUserByUsername function call and causes the entire thing to shutdown. The other cases are fine, bad request, server errors etc.


Solution

  • You're almost there, but I do see a couple of small issues that may be the cause.

    1. Inside your getUserByUsername fn, you are not returning anything if a user is not found.

    You have:

    async function getUserByUsername(username) {
            try {
                // Find a user record with the specified username
                const foundUser = await User.findOne({
                    where: {
                        username: username
                    }
                });
        
                // Check if the user was found
                if (foundUser) {
                    return true;
                } else {
                    false; <--- THIS
                }
            } catch (error) {
                console.error('Error finding user:', error);
            }
        }
    
    1. .sendStatus ends responses, so chaining json behind it will have no effect. Try using .status() before chaining json() instead.

    Like so:

    if(await getUserByUsername(user.username)){
       res.status(409).json({"message": "user already exists"});
       return;
    }
    

    I hope this works for you. Good luck!