1

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'
            });
Nimish Agrawal
  • 511
  • 1
  • 5
  • 11
  • Hi Nimish, Any solution you found ? I am facing exactly same issue and unable to reproduce it for particular scenario. I have opened defect against NPM repository for help. – Rajjy Sep 09 '20 at 04:40
  • @Rajjy can you check if ending the connection helps. – Nimish Agrawal Sep 10 '20 at 05:17

2 Answers2

1

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.

Nimish Agrawal
  • 511
  • 1
  • 5
  • 11
0

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
    });
Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67