-1

So I am trying to make a post request via jquery and then console.log the data object in the callback function of the request. client-side:

var save = $('<button/>',{
        class: 'btn btn-link',
        id: url,
        type: 'submit',
        value: 'Submit',
        text: 'save for later?',
        click: function(event){
            var reqData = { article : this.id};
            $.post('/profile', reqData, function(data){
                console.log(data);
            })
        }

server-side:

router.post('/profile', function(req, res) {
console.log(req.body);
// User.find();
console.log(req.user._id);
var article = new Article({article: req.body.article});


article.save(function(error, doc) {
        if (error) {
            res.send(error);
        } else {

            var id = doc._id;
            User.findOneAndUpdate({
                _id: req.user._id
            }, {$push :{
                article: id
            }}).exec(function(err, doc) {
                if (err) {
                    res.send(err);
                } else {
                   res.send(doc);
                }
            })
            res.send(doc);
        }
})

I keep getting the error message 'can't set headers after they are sent', and if I comment out the res.send(doc); within the .exec promise, then the data will console.log, but the page will quickly refresh and erase it.

dalt25
  • 27
  • 9
  • It looks like you're calling `res.send(doc)` twice. Remove the call at the bottom. To avoid the page reloading I guess you need to call `event.preventDefault();` in your button's click handler. –  Sep 26 '17 at 21:51
  • You are sending the response in a promise and after it too, it's normal, you have a second send when it sent previously – Kalamarico Sep 26 '17 at 21:51
  • event.preventDefault did the trick. I'm building an app (which for the most part works) and it has been a great refresher for jQuery and I guess event.preventDefault slipped my mind, I know this question was simple, and I'll keep in mind to ask more thoughtful questions in the future. – dalt25 Sep 26 '17 at 22:07

1 Answers1

-1

The error 'can't set headers after they are sent' means that you are trying to respond multiple times. The final res.send is being sent initially, and then once the exec callback's if/else is evaluated, a second res.send is attempted.

bazzells
  • 329
  • 2
  • 8
  • Ok, I see it more clearly I know the question was simple, I was just stuck with two different scenarios. – dalt25 Sep 26 '17 at 22:03