2016-08-04 101 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響應發送回所需要的狀態代碼。

也可以考慮在代碼中只使用單引號或雙引號來保持一致性。