1

I have written the following code to check whether an api request is from the correct location and user pair. For some reason the chain doesn't stop at return, so the code tries to execute the controller (failing with 'ERR_HTTP_HEADERS_SENT'), but the caller gets the message "Location not matching user".

isClaimedLocation = (req, res, next) => {
    if (!req.body.location) {
        res.status(403).send({ message: "No location data included." });
        return;
    }
    User.findById(req.userId).then(user => {
        Role.find({
            _id: { $in: user.roles }
        }).then(roles => {
            let found = false;
            for (let i = 0; i < roles.length; i++) {
                if (roles[i].name === "location") {
                    found = true;
                    Location.findOne({
                        name: req.body.location
                    }).then(location => {
                        if (!location) {
                            res.status(400).send({ message: "Location does not exist." });
                            return;
                        }
                        if (!location.userref._id.equals(user._id)) {
                            res.status(403).send({ message: "Location not matching user!" });
                            return;
                        }
                    }).catch(err => {
                        if (err) {
                            res.status(500).send({ message: err });
                            return;
                        }
                    });
                }
            }
            if (!found) {
                res.status(403).send({ message: "Require Location Role!" });
                return;
            }
            else {
                next();
            }
        }).catch(err => {
            res.status(500).send({ message: err });
            return;
        });
    }).catch(err => {
        if (err) {
            res.status(500).send({ message: err });
            return;
        }
    });
};

I tried looking around Stack Overflow and the code, and changing things like putting a variable to track if there is a problem, and only if not, then call next, but I have failed miserably.

  • https://stackoverflow.com/questions/52122272/err-http-headers-sent-cannot-set-headers-after-they-are-sent-to-the-client this might help? – cmgchess Apr 15 '23 at 15:16
  • 2
    a `.then` in `for` loop is not synchronous, so it's going to fire the `res.status(400).send`'s multiple times, your code would be cleaner and less nested and deduplicated if you use async/await – Lawrence Cherone Apr 15 '23 at 15:22
  • @LawrenceCherone solution was correct I think. I basically had to skip the for loop somehow – John Andrew Kypriotakis Apr 15 '23 at 15:43

0 Answers0