简体   繁体   中英

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

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?

In your code you have this...

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')

your error says

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

this happens because you are calling two times the res.json or res.status.

Ex1: When you call your endpoint you enter the if conditional and you call the res.json('success');(the headers have been send to the client). Then you call again res.json('signing') and in that moment the error is thrown.

Ex2: When you call your endpoint you enter the else conditional and you call the res.status(400).json('error logging in'); (the headers have been send to the client). Then you call again res.json('signing') and in that moment the error is thrown.

You should delete the last res.json('signing').

Imagine that you would like to send more thing you may want to sent a response like this:

res.json({message:'success', x:'signing'})
// or
res.status(400).json({error: 'error logging in', x: 'signing'})

Hope this is helpful: If someone finds something to make better this answer feel free to comment :D

In the if conditional use return while sending the response. Example is given below.

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

return res.json('success');

} else {

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

}  

The error is happening because you are trying to send a response after a response has already been sent.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM