2016-08-04 102 views
1

我想在两种情况下使用错误函数将JSON错误对象传入我的代码中。一旦在电子邮件和密码检查语句中,并再次在if现有用户语句中。我想那只是晚上的那个时间。错误函数不返回JSON格式

const User = require('../models/user'); 

exports.signup = function(req, res, next) { 
    const email = req.body.email; 
    const password = req.body.password; 

    if (!email || !password) { 
     return res.err("Please enter in email and password"); 
    } 

    //See if a user with the given email exists 
    User.findOne({ email: email }, function(err, existingUser) { 
     if (err) { return next(err); } 

     //If a user with email does exist, return an Error 
     if (existingUser) { 
     //the status sets the status of the http code 422 means couldn't process this 
      return res.err('Email is in use'); 
     } 
     //If a user with email does NOT exist, create and save user record 
     const user = new User({ 
      email: email, 
      password: password 
     }); 

     user.save(function(err) { 
      if (err) { return next(err); } 
      //Respond to request indicating the user was created 
      res.json({ success: true }); 
     }); 
    }); 
} 
+0

你是怎么回事? – alexi2

回答

1

在你是不是在你的回应返回正确的状态码的时候,你可以试试这个:

替换:

return res.err("Please enter in email and password");

随着

return res.status(422).send({error: "Please enter in email and password"})

并替换:

return res.err('Email is in use');

有了:

return res.status(422).send({ error: "Email is in use" });

这将在HTTP响应发送回所需要的状态代码。

也可以考虑在代码中只使用单引号或双引号来保持一致性。