json - 错误函数未返回 JSON 格式

标签 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 });
        });
    });
}

最佳答案

目前您在响应中没有返回正确的状态代码,您可以尝试以下操作:

替换:

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/

相关文章:

Node.js module.exports 函数从 MongoDB 返回数组

javascript - 无法使用express加载静态文件

PHP、MYSQL、JSOn社交网站快速搜索功能技巧

node.js - nodejs 如何使用 puppeteer-core 修复 `browser.newPage is not a function`?

javascript - 无法读取未定义的属性 'fetch'

javascript - 使用 ES6 Promises 惯用地处理前置条件

Node.js API 与 Express 异步 : Trouble with multiple request

c# - 我的 Azure DocumentDB 文档类是否应该继承自 Microsoft.Azure.Documents.Document?

java - 使用 Jackson 数据绑定(bind)跳过嵌套字段?

php - Symfony 5 - 使用 json_login 登录;登录过程不工作;