Can't set headers after they are sent node js

2019-06-09 07:17发布

问题:

I'm trying to send some form data, but I get this error using express.js:

Can't set headers after they are sent.

This is my code so far:

app.post('/api/users/profile/:username', isAuthenticated, userUploads, function(req, res, next) {
    if (req.params.username) {
        User.findOne({ username: req.params.username }, function(err, user) {
            if (err) return next(err);
            user.profile.name = req.body.name;
            user.profile.gender = req.body.gender;

            var files = req.files.file;
            if (files){
                if (files.length > 0){
                    for (f in files){
                        user.profile.pictures.push(files[f])
                    }
                }else{
                    user.profile.pictures.push(files)
                }
            }
            user.save(function(err) {
                if (err) return next(err);
                res.send(200);
            });

            console.log(res.send(user)) //HERE IS WHERE I GET THE ERROR

        });
    }else{
        return res.send(400, { message: 'User does not exist!!' });
    }
});

回答1:

By console logging res.send(user) you are sending again. You can send once and once only.

app.post('/api/users/profile/:username', isAuthenticated, userUploads, function(req, res, next) {
    if (req.params.username) {
        User.findOne({ username: req.params.username }, function(err, user) {
            if (err) return next(err);
            user.profile.name = req.body.name;
            user.profile.gender = req.body.gender;

            var files = req.files.file;
            if (files){
                if (files.length > 0){
                    for (f in files){
                        user.profile.pictures.push(files[f])
                    }
                }else{
                    user.profile.pictures.push(files)
                }

            }
            user.save(function(err) {
                if (err) return next(err);
                res.status(200).send(user);
            });

        });
    }else{
        return res.send(400, { message: 'User does not exist!!' });
    }
});