Jon Doe
Jon Doe

Reputation: 389

Cannot set headers after they are sent to the client NodeJS

I am writing some Node JS API for login. I have written the logic but I am encountering an issue when I am sending back the response. Here is my code:

app.post('/API/login', (request, response) => {
    model.findOne({ email: request.body.email }, (err, result) => {
        if (err) throw err;

        if (result) {
            bcrypt.compare(request.body.password, result.password, function (error, hash) {
                if (error) throw err;
                if (hash) {
                    request.session.logged = true;
                    request.session._id = result._id;
                    response.send(result._id);
                }
                else {
                    response.send('Incorrect Username and/or Password!');
                }
            })
        } else {
            response.send('Incorrect Username and/or Password!');
        }
        response.end();
    })
});

However, I am encountering a problem. I keep getting the following error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (node_modules\express\lib\response.js:775:10)
    at ServerResponse.json (node_modules\express\lib\response.js:268:10)
    at ServerResponse.send node_modules\express\lib\response.js:162:21
    at login.js:73:34
    at node_modules\bcryptjs\dist\bcrypt.js:297:21
    at node_modules\bcryptjs\dist\bcrypt.js:1353:21
    at Immediate.next (node_modules\bcryptjs\dist\bcrypt.js:1233:21)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)

I am not sure what is causing this issue.

Upvotes: 0

Views: 300

Answers (1)

Murat
Murat

Reputation: 1205

You are trying to send a response with response.end() after you've already answered with response.send(...)

You can delete the response.end()statement :

app.post('/API/login', (request, response) => {
  model.findOne({ email: request.body.email }, (err, result) => {
    if (err) throw err;

    if (result) {
        bcrypt.compare(request.body.password, result.password, function (error, hash) {
            if (error) throw err;
            if (hash) {
                request.session.logged = true;
                request.session._id = result._id;
                response.send(result._id);
            }
            else {
                response.send('Incorrect Username and/or Password!');
            }
        })
    } else {
        response.send('Incorrect Username and/or Password!');
    }
  })
});

Upvotes: 1

Related Questions