0

I need to user diferents response.redirect() but I get an error in my console.

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

My code :

 // on vérifie si max par semaine atteint si c'est le cas on supprime la resa if (moment(createdItem.date).isSame(new Date(), 'week')) { createdItem.destroy().then(function() { request.flash('danger', 'Total de réservation maximum par semaine atteint'); response.redirect('/user/__show'); }); } // dans le cas d'un abonnement trouvé on touche pas aux cartes if (findedRpaUserServiceSub) { request.flash('success', 'Réservation ajoutée'); response.redirect('/user/__show'); } // si on trouve une carte mais sans abonnement if (findedRpaUserServiceCard) { if ((findedRpaUserServiceCard.remaining_services - 1) === 0) { findedRpaUserServiceCard.destroy().then(function() { request.flash('success', 'Réservation ajoutée'); response.redirect('/user/__show'); }); } else { findedRpaUserServiceCard.update({ remaining_services: findedRpaUserServiceCard.remaining_services - 1 }).then(function() { request.flash('success', 'Réservation ajoutée'); response.redirect('/user/__show'); }); } } 

1 Answer 1

1

You are redirecting the user multiple times. These if are not exclusives. You should, at minima, use else if statement

// on vérifie si max par semaine atteint si c'est le cas on supprime la resa if (moment(createdItem.date).isSame(new Date(), 'week')) { createdItem.destroy().then(function() { request.flash('danger', 'Total de réservation maximum par semaine atteint'); response.redirect('/user/__show'); }); } // dans le cas d'un abonnement trouvé on touche pas aux cartes else if (findedRpaUserServiceSub) { request.flash('success', 'Réservation ajoutée'); response.redirect('/user/__show'); } // si on trouve une carte mais sans abonnement else if (findedRpaUserServiceCard) { if ((findedRpaUserServiceCard.remaining_services - 1) === 0) { findedRpaUserServiceCard.destroy().then(function() { request.flash('success', 'Réservation ajoutée'); response.redirect('/user/__show'); }); } else { findedRpaUserServiceCard.update({ remaining_services: findedRpaUserServiceCard.remaining_services - 1 }).then(function() { request.flash('success', 'Réservation ajoutée'); response.redirect('/user/__show'); }); } } else { // something else } 

You can also add a return inside each if to stop further processing or use next() if you are using expressjs to go to the next middleware.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.