错误函数不返回JSON格式

时间:2016-08-04 03:36:46

标签: json node.js express

我试图在两种情况下使用错误函数将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 });
        });
    });
}

1 个答案:

答案 0 :(得分: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响应中发回所需的状态代码。

还要考虑在代码中仅使用单引号或双引号来保持一致性。