没有路由器/子网站表示发布500错误

时间:2016-11-08 19:43:39

标签: node.js express angular

我的设置如下:

张贴到/register将接受参数并通过护照和mongoose注册用户。如果返回UserExistsError,则服务器将此信息发送给客户端(通过http错误处理)。

但是,服务器还会显示500服务器错误,该错误不应发生。

这是因为next()据我所知,将客户端路由到/register/register本身不作为页面存在(仅作为代码中所述的postadress)

所以我的问题是:如何处理不是错误或压制它的响应?我可以使用其他内容而不是next()来停止重定向到/register吗?我只是希望服务器在那时停止做任何事情/退出该功能。

代码:

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 '/'
    }
  });
});

这个话题让我烦恼,我可能只是想念一些微不足道的事情。

1 个答案:

答案 0 :(得分:1)

即使/register是仅发布路线,您仍需要发送回复。如果您没有发送某种响应,请求将挂起并最终在浏览器中超时。我建议像这样发送一个json响应。

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'});
  });
});

这会发出一个200 OK响应,身体里有一些json。

如果您只想将请求传递到该行,则需要在没有错误对象的情况下调用下一行。

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();
  });
});

我不确定这是否是您要实现的目标,但如果没有匹配的路线,则只会出现错误500.