Cannot set headers after they are sent to the client - error

Question

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

`at ServerResponse.setHeader (_http_outgoing.js:558:11)

    at ServerResponse.header (D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\node_modules\express\lib\response.js:771:10)

    at ServerResponse.send (D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\node_modules\express\lib\response.js:170:12)

    at ServerResponse.json (D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\node_modules\express\lib\response.js:267:15)

    at D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\server.js:57:6

    at Layer.handle [as handle_request] (D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\node_modules\express\lib\router\layer.js:95:5)

    at next (D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\node_modules\express\lib\router\route.js:137:13)

    at Route.dispatch (D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\node_modules\express\lib\router\route.js:112:3)

    at Layer.handle [as handle_request] (D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\node_modules\express\lib\router\layer.js:95:5)

    at D:\D\Coding\Web Development\Final Project\Face Detection\facerecognitionbrain-api\node_modules\express\lib\router\index.js:281:22`
`const express = require('express');

const bodyParser = require('body-parser');

const bcrypt = require('bcrypt-nodejs');

const app = express();

app.use(bodyParser.json());

const database = {
  users: [
    {
      id: '123',
      name: 'John',
      email: 'john@gmail.com',
      entries: 0,
      joined: new Date()
    },
    {
      id: '124',
      name: 'sally',
      email: 'sally@gmail.com',
      entries: 0,
      joined: new Date()
    }
  ],
  login: [
    {
      id: '987',
      hash: '',
      email: 'john@gmail.com'
    }
  ]
}

app.get('/', (req,res) =>{

res.send(database.users);

})

app.post('/signin', (req, res)=>{

bcrypt.compare("apple", '$2a$10$r145GrmmFJAaiRF3Gn3eEuTRS69chhTOYS9sAhiACyiV7oe/vbFyO', function(err, res) {

    console.log('first guess', res);

});

bcrypt.compare("veggies", '$2a$10$r145GrmmFJAaiRF3Gn3eEuTRS69chhTOYS9sAhiACyiV7oe/vbFyO', function(err, res) {

    console.log('second guess', res);

});

if(req.body.email === database.users[0].email &&

req.body.password === database.users[0].password){

res.json('success');

}

else{

res.status(400).json('error logging in');

}

res.json('signing')

})

app.post('/register', (req,res)=>{

const {email, name, password} = req.body;

bcrypt.hash(password, null, null, function(err, hash) {

console.log(hash);

});

database.users.push({

id: '125',

name: name,

email: email,

password: password,

entries: 0,

joined: new Date()

})

res.json(database.users[database.users.length - 1]);

})

app.get('/profile/:id', (req,res)=>{

const{ id } = req.params;

let found = false;

database.users.forEach(users =>{

if(users.id === id){

found = true;

return res.json(users);

}

})

if(!found){

req.status(400).json('not found')

}

})

app.post('/image', (req,res) => {

const{ id } = req.body;

let found = false;

database.users.forEach(users =>{

if(users.id === id){

found = true;

users.entries++;

return res.json(users.entries);

}

})

if(!found){

res.status(400).json('not found')

}

})

app.listen(3000, ()=>{

console.log('app is running on port 3000');

})`

This is the code.... what shout i do?

Answer

Problematic line of code: res.json('signing')

Why is it an issue?: You are attempting to send 2 responses to a client for 1 request.

The first response that is being sent out, is in your conditional statement and it sets headers (things like response status 200 if successful etc), after execution of your conditional statement, the line highlighted above, attempts to send another response to the client and also set headers again, hence the error message (Cannot set headers after they are sent to the client)

You can try the suggestion below:

`if (
  req.body.email === database.users[0].email &&
  req.body.password === database.users[0].password
) {
  return res.status(200).json({
    title: 'Success',
    message: 'Signing',
  });
}

return res.status(400).json('error logging in');`
```

> This answer was originally posted on Stack Overflow. You can find the full discussion [here](https://stackoverflow.com/a/67332379).

Related Posts

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

## Question Can one transfer repositories from GitLab to GitHub if the need be. If so, how exactly can I go about doing the same? Also, are there any pitfalls in doing so or precautionary measures

Read More

Cannot set headers after they are sent to the client - error

## Question Error `[ERR_HTTP_HEADERS_SENT]`: Cannot set headers after they are sent to the client ```text `at ServerResponse.setHeader (_http_outgoing.js:558:11) at ServerResponse.header (D:\D

Read More

Pulling data with 'Where' and 'Include' statements at the same time

## Question I have managed to get my include statements working with my foreign keys however when I try to add a 'where' statement to the findAll statement I am getting the below error. I have check

Read More