Wandang Wandang - 29 days ago 8
Node.js Question

express post 500 error without router/subsite

My setup is as follows:

posting to

/register
will take the arguments and register a user via passport and mongoose. If this returns an
UserExistsError
the server sends this info to the client (via http error handling).

However the server also displays a 500 server error which should not occur.

This is because of the
next()
which as far as I understand routes the client to
/register
.
/register
itself does not exists as a page (only as the postadress as stated in the code)

So my question is: How to handle the response to not be an error or supress it? Can I use something else instead of next() to stop the redirect to
/register
? I just want the server to stop doing anything/going out of that function at that point.

Code:

app.post('/register', function(req, res, next) {
console.log('server registering user');
User.register(new User({username: req.body.username}), req.body.password, function(err) {
let tempstring = ""+err;
if(tempstring.indexOf("UserExistsError") !== -1){
return next(err); //get out of the function and into normal operation under '/'
}
});
});


This topic is bugging me and I might just missunderstand something trivial.

Answer

Even if /register is a post only route you still need to send a response. If you don't send a response of some kind, the request will hang and eventually timeout in the browser. I would suggest sending a json response like so.

app.post('/register', function(req, res, next) {
  console.log('server registering user');
  User.register(new User({username: req.body.username}), req.body.password, function(err) {
    let tempstring = ""+err;
    if(tempstring.indexOf("UserExistsError") !== -1){
      return next(err); //get out of the function and into normal operation under '/'
    }
    res.json({message: 'message here'});
  });
});

This will send a 200 OK reponse with some json in the body.

If you just want to pass the request down the line you need to call next without an err object like so.

app.post('/register', function(req, res, next) {
  console.log('server registering user');
  User.register(new User({username: req.body.username}), req.body.password, function(err) {
    let tempstring = ""+err;
    if(tempstring.indexOf("UserExistsError") !== -1){
      return next(err); //get out of the function and into normal operation under '/'
    }
    //call next without an error
    next();
  });
});

I am not sure if this is what you are trying to achieve, but if there is no route that matches it will just go to an error 500.