[Fixed] Express headers error when sending request

Issue

An error "[ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client" occurs when requesting this method. I just got acquainted with express and quite possibly succeeded in doing something. Tell me what causes the error

const generateAccessToken = (id,username) => {
    const payload = {
        id,
        username
    }
    return jwt.sign(payload, secret, {expiresIn: "24h"});
}



async login(req, res) {
        try {
            const {username, password} = req.body;
            pool.query('SELECT * FROM users', (error, result) => {
                if(error) return console.log(error);

                result.map(item => {

                    if (item.username !== username) {
                        return res.status(400).json({message: 'Error username'});
                    }

                    const validPassword = bcrypt.compareSync(password, item.password);

                     if (!validPassword) {
                        return res.status(400).json({message: 'Error password'});
                    }

                    const token = generateAccessToken(item.id,item.username);
                    return res.json({token});

                });
            });
        } catch (e) {
            console.log(e);
            res.status(400).json({message: 'Login error'});
        }
    }

Solution

You are writing to the response inside of your .map, so it is writing the headers multiple times, and you’re only allowed to do that once.

Quick glance indicates you probably want to do something like:

pool.query('SELECT * FROM users WHERE username=:username', { replacements: { username }})

but I’m not sure what sql driver you are using or how it handles binding parameters, or whether you have a unique index on your username column, etc.

Leave a Reply

(*) Required, Your email will not be published