NodeJS用户注册/验证器

时间:2018-10-18 11:56:04

标签: javascript node.js

我正在构建NodeJS / Express身份验证,并尝试进行一些异步/等待(尝试/捕获),然后在添加验证之前,我的注册路由可以正常工作。问题是我的validaiton(基于验证器)正在运行,正在按预期发送回错误,但是当我有正确的数据来注册用户时。邮递员还给我空的物品。没有错误。我假设此try / catch的工作方式与之前使用的.then()不同。

致谢

auth.js 注册路线

const db = require('../models')
const validateRegisterInput = require('../validation/register')


exports.register = async (req, res, next) => {
    const {
        errors,
        isValid
    } = validateRegisterInput(req.body)

    if (!isValid) {
        return res.status(400).json(errors)
    }
    try {
        const user = await db.User.create(req.body)
        const {
            id,
            username
        } = user
        res.json({
            id,
            username
        })
    } catch (error) {
        return next(error)
    }
}

注册验证

const validator = require('validator')
const isEmpty = require('./is-empty')

const validateRegisterInput = (data) => {
    let errors = {}

    data.username = !isEmpty(data.username) ? data.username : ''
    data.password = !isEmpty(data.password) ? data.password : ''

    if (!validator.isLength(data.username, {
            min: 2,
            max: 30
        })) {
        errors.username = 'Username should be between 2 and 30 characters'
    }
    if (validator.isEmpty(data.username)) {
        errors.username = 'Username is required'
    }
    if (validator.isEmpty(data.password)) {
        errors.password = 'Password is required'
    }
    if (!validator.isLength(data.password, {
            min: 6,
            max: 30
        })) {
        errors.password = 'Password should be at least 6 characters'
    }
    return {
        errors,
        isValid: isEmpty(errors)
    }
}

module.exports = validateRegisterInput

isEMpty

const isEmpty = (value) => {
    value === undefined ||
        value === null ||
        (typeof value === 'object' && Object.keys(value).length === 0) ||
        (typeof value === 'string' && value.trim().length === 0)
}

module.exports = isEmpty

1 个答案:

答案 0 :(得分:1)

isEmpty缺少返回值-因此总是返回undefined并将返回结果为false的返回值。 或者-除了添加return之外,您当然可以删除括号{...}