我尝试在两种情况下使用错误函数将 JSON 错误对象传递到我的代码中。一次是在电子邮件和密码检查语句中,另一次是在 if existingUser 语句中。我想这只是晚上的那个时间。
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 });
});
});
}
最佳答案
目前您在响应中没有返回正确的状态代码,您可以尝试以下操作:
替换:
return res.err("请输入邮箱和密码");
与
return res.status(422).send({error: "请输入电子邮件和密码"})
并替换:
return res.err( '电子邮件正在使用' );
与:
return res.status(422).send({ error: "电子邮件正在使用"});
这将在 http 响应中发回所需的状态代码。
还请考虑在代码中仅使用单引号或双引号以保持一致性。
关于json - 错误函数未返回 JSON 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38758085/