0

I am trying to output specific messages on specific responses.

Here is my code:

.post(function(req, res) {
  var user = new User(req.body);

  user.save(function(err) {
    if(err) {
      if(err.code == 11000)
        res.status(409).json(customHTTPcodeReponses.exists(req.body.email));
    };

    User.findById(user._id, function(err, createdUser) {
      res.status(201).json(customHTTPcodeReponses.created(createdUser));
    });
  });
});

Flow:

  1. Posting data. I get 201.
  2. Posting same data again. I get 409.
  3. Posting same data again. I get "Could not get any response (POSTMAN)"

Console error: _http_outgoing.js:335 throw new Error('Can\'t set headers after they are sent.'); [nodemon] app crashed - waiting for file changes before starting...

What could cause this?

6
  • "does not work" - elaborate Commented Sep 19, 2015 at 9:54
  • I think this question can helps ;). Commented Sep 19, 2015 at 10:01
  • I have changed description. Can you please look at it again? Commented Sep 19, 2015 at 12:13
  • 1
    Did you try adding the User.findById code within an else statement? (if(err){ .... } else { User.findById........ }) Commented Sep 19, 2015 at 15:34
  • @shan1024 thank you, I did not realised res can be called twice. I avoided this by typing in return as result of if(err). But I could use else statement as well. Commented Sep 21, 2015 at 15:14

1 Answer 1

1

Add the User.findById code within an else statement.

user.save(function(err) {
    if(err) {
      if(err.code == 11000)
        res.status(409).json(customHTTPcodeReponses.exists(req.body.email));
    }else{
        User.findById(user._id, function(err, createdUser) {
           res.status(201).json(customHTTPcodeReponses.created(createdUser));
        });
    }
  });

or add a return to the 1st response:

if(err.code == 11000)
    return res.status(409).json(customHTTPcodeReponses.exists(req.body.email));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.