简体   繁体   中英

How to stop double sending the headers in node express?

I'm receiving error "Can't set headers after they are sent to the client". and i found out the my code are trying to send 2 response that trying to modify the previous set of headers.

To solve the issue I put return keyword to stop the function execution and stop the 2nd "res". however is there a fancier way or more node express way to do it?

here is my current solution.

if(!err && goal) {
                if(goal.currentValue >= goal.targetValue) {//check if status is completed currentValue >= targetValue
                    models.Goal.findOneAndUpdate(
                        { _id: goal._id },
                        { $set: { isCompleted: true }},
                        { useFindAndModify: false, new: true },
                        (err, goal) => {

                            if(err)  res.status(500).json({ message: `Update failed. ${err}`});
                            else if(goal.isCompleted) res.status(200).json({ message: 'Goal is completed' });
                        });
                        return  //I used return to stop from executing the 2nd calling of res.status(200)....               
                }
                res.status(200).json({ message: `Goal progress has been updated`});
            }

Try out by putting else .

       if(!err && goal) {
            if(goal.currentValue >= goal.targetValue) 
{//check if status is completed currentValue >= targetValue
                                    models.Goal.findOneAndUpdate(
                                        { _id: goal._id },
                                        { $set: { isCompleted: true }},
                                        { useFindAndModify: false, new: true },
                                        (err, goal) => {

                                            if(err)  res.status(500).json({ message: `Update failed. ${err}`});
                                            else if(goal.isCompleted) res.status(200).json({ message: 'Goal is completed' });
                               else{
                                   res.status(200).json({ message: `Goal progress has been updated`});
                                }
                                        });

                                }


                            }

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