0

I am getting an error:

Error: Can't set headers after they are sent at
ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)

My Api

exports.signUp = function(req,res,next) {
    var userCredentials = new userModel.User({
        user_name: req.body.userName,
        email: req.body.email,
        password: req.body.password
    })
    userLib.getUserByEmail(req.body.email, function (err,result) {
        console.log(err,result)
        if(result && err==null) {
          res.json({status:"emailAlreadyRegistered"});
        }
        else {
          userCredentials.save(function(error,result) {
            if(error == "error"){
              return res.status(500).json({status:"error"});
            }
            return res.status(200).json({status:"success"});
          })
        }
    });
}

I find that the issue is in .save(()=>{}) . While checking with postman It works fine for first input.sent {status:"success"} response.

Issue

If I send the request once again it will give an error Error: Can't set headers after they are sent

How do I fix it?

Thanks in advance

euvl
  • 4,716
  • 2
  • 25
  • 30
  • i tried https://stackoverflow.com/questions/43009676/nodejs-can-t-set-headers-after-they-are-sent , https://stackoverflow.com/questions/21459697/node-js-http-js691-throw-new-errorcan-t-set-headers-after-they-are-sent , https://stackoverflow.com/questions/26262745/node-js-express-timeout-can-t-set-headers-after-they-are-sent , https://stackoverflow.com/questions/26961421/can-t-set-headers-after-they-are-sent – Mohanraj S Aug 01 '17 at 05:07
  • use this [ans](https://stackoverflow.com/a/7086621/7808007) you will get solution and better knowledge – kumbhani bhavesh Aug 01 '17 at 05:38
  • so u **/signUp** calls this signUp function? – manish kumar Aug 01 '17 at 05:51
  • tq @kumbhaniBhavesh – Mohanraj S Aug 01 '17 at 06:37

1 Answers1

-1

Node js will set header and is not destroyed until the response ends. so below is my sos:

Ans

userCredentials.save(function(error,result) {
            if(error == "error"){
              return res.status(500).json({status:"error"});
              res.end();
            }
            return res.status(200).json({status:"success"});
            res.end();
          })
        }

It Works for me.