📌  相关文章
📜  如何检查电子邮件地址是否已在使用或未在 Node.js 中使用 express-validator?

📅  最后修改于: 2022-05-13 01:56:40.685000             🧑  作者: Mango

如何检查电子邮件地址是否已在使用或未在 Node.js 中使用 express-validator?

任何网站的注册或注册都需要用户名。大多数时候,我们使用“电子邮件”在网站上注册。注册电子邮件始终是唯一的,并且必须仅引用一个用户,否则可能会发生用户之间的冲突。为了解决这个冲突,每个网站都必须具有不接受网站上已经存在的电子邮件的功能。此功能可以在我们的代码中的任何位置实现,例如在索引文件或路由文件中,但这属于验证部分。所以我们通常更喜欢在所有其他验证都被编码的地方编码这个逻辑。这里我们使用“express-validator”中间件来实现这个功能。

安装 express-validator 的命令:

npm install express-validator

使用 express-validator 实现逻辑的步骤:

  • 安装 express-validator 中间件。
  • 创建一个validator.js 文件来编码所有的验证逻辑。
  • 通过validateEmail验证电子邮件: check('email')并使用 ' 链接所有验证 '
  • 使用路由中的验证名称(validateEmail)作为验证数组的中间件。
  • 从 express-validator 中解构 'validationResult'函数以使用它来查找任何错误。
  • 如果发生错误,则重定向到传递错误信息的同一页面。
  • 如果错误列表为空,则授予用户后续请求的访问权限。

注意:这里我们使用本地或自定义数据库来实现逻辑,可以按照相同的步骤在MongoDB或MySql等常规数据库中实现逻辑。

示例:此示例说明如何检查电子邮件地址是否已用于特定网站。

文件名:index.js

javascript
const express = require('express')
const bodyParser = require('body-parser')
const { validationResult } = require('express-validator')
const repo = require('./repository')
const { validateEmail } = require('./validator')
const signupTemplet = require('./signup')
 
const app = express()
 
const port = process.env.PORT || 3000
 
// The body-parser middleware to parse form data
app.use(bodyParser.urlencoded({ extended: true }))
 
// Get route to display HTML form to sign up
app.get('/signup', (req, res) => {
    res.send(signupTemplet({}))
})
 
// Post route to handle form submission logic and
app.post(
    '/signup',
    [validateEmail],
    async (req, res) => {
        const errors = validationResult(req)
        if (!errors.isEmpty()) {
            return res.send(signupTemplet({ errors }))
        }
        const { email, password } = req.body
        await repo.create({ email, password })
        res.send('Sign Up successfully')
    })
 
// Server setup
app.listen(port, () => {
    console.log(`Server start on port ${port}`)
})


javascript
// Importing node.js file system module
const fs = require('fs')
 
class Repository {
 
    constructor(filename) {
 
        // The filename where datas are
        // going to store
        if (!filename) {
            throw new Error(
'Filename is required to create a datastore!')
        }
 
        this.filename = filename
 
        try {
            fs.accessSync(this.filename)
        } catch (err) {
 
            // If file not exist it is created
            // with empty array
            fs.writeFileSync(this.filename, '[]')
        }
    }
 
    // Get all existing records
    async getAll() {
        return JSON.parse(
            await fs.promises.readFile(this.filename, {
                encoding: 'utf8'
            })
        )
    }
 
    // Find record by properties
    async getOneBy(filters) {
        const records = await this.getAll()
        for (let record of records) {
            let found = true
            for (let key in filters) {
                if (record[key] !== filters[key]) {
                    found = false
                }
            }
            if (found) return record;
        }
    }
 
    // Create new record
    async create(attrs) {
        const records = await this.getAll()
        records.push(attrs)
        await fs.promises.writeFile(
            this.filename,
            JSON.stringify(records, null, 2)
        )
        return attrs
    }
}
 
// The 'datastore.json' file created at runtime
// and all the information provided via signup form
// store in this file in JSON format.
module.exports = new Repository('datastore.json')


javascript
const getError = (errors, prop) => {
    try {
 
        // Return error message if any error occurs
        return errors.mapped()[prop].msg
    } catch (error) {
 
        // Return empty string if no error
        return ''
    }
}
 
module.exports = ({ errors }) => {
    return `
      
      
        
          
          
        
        
          
            
              
                

Sign Up

                
                               
                    
                                           
                                         

                        ${getError(errors, 'email')}                     

                  
                  
                    
                                             
                                       
                  
                                       
                
              

            
          
                      ` }


javascript
const { check } = require('express-validator')
const repo = require('./repository')
 
module.exports = {
 
    validateEmail: check('email')
 
        // To delete leading and triling space
        .trim()
 
        // Normalizing the email address
        .normalizeEmail()
 
        // Checking if follow the email
        // address format or not
        .isEmail()
 
        // Custom message
        .withMessage('Invalid email')
 
        // Custom validation
        // Validate email in use or not
        .custom(async (email) => {
            const existingUser =
                await repo.getOneBy({ email })
                 
            if (existingUser) {
                throw new Error('Email already in use')
            }
        })
}


文件名:repository.js此文件包含创建本地数据库并与之交互的所有逻辑。

javascript

// Importing node.js file system module
const fs = require('fs')
 
class Repository {
 
    constructor(filename) {
 
        // The filename where datas are
        // going to store
        if (!filename) {
            throw new Error(
'Filename is required to create a datastore!')
        }
 
        this.filename = filename
 
        try {
            fs.accessSync(this.filename)
        } catch (err) {
 
            // If file not exist it is created
            // with empty array
            fs.writeFileSync(this.filename, '[]')
        }
    }
 
    // Get all existing records
    async getAll() {
        return JSON.parse(
            await fs.promises.readFile(this.filename, {
                encoding: 'utf8'
            })
        )
    }
 
    // Find record by properties
    async getOneBy(filters) {
        const records = await this.getAll()
        for (let record of records) {
            let found = true
            for (let key in filters) {
                if (record[key] !== filters[key]) {
                    found = false
                }
            }
            if (found) return record;
        }
    }
 
    // Create new record
    async create(attrs) {
        const records = await this.getAll()
        records.push(attrs)
        await fs.promises.writeFile(
            this.filename,
            JSON.stringify(records, null, 2)
        )
        return attrs
    }
}
 
// The 'datastore.json' file created at runtime
// and all the information provided via signup form
// store in this file in JSON format.
module.exports = new Repository('datastore.json')

文件名:signup.js此文件包含显示注册表单的逻辑。

javascript

const getError = (errors, prop) => {
    try {
 
        // Return error message if any error occurs
        return errors.mapped()[prop].msg
    } catch (error) {
 
        // Return empty string if no error
        return ''
    }
}
 
module.exports = ({ errors }) => {
    return `
      
      
        
          
          
        
        
          
            
              
                

Sign Up

                
                               
                    
                                           
                                         

                        ${getError(errors, 'email')}                     

                  
                  
                    
                                             
                                       
                  
                                       
                
              

            
          
                      ` }

文件名:validator.js此文件包含所有验证逻辑(逻辑查看电子邮件是否已存在)。

javascript

const { check } = require('express-validator')
const repo = require('./repository')
 
module.exports = {
 
    validateEmail: check('email')
 
        // To delete leading and triling space
        .trim()
 
        // Normalizing the email address
        .normalizeEmail()
 
        // Checking if follow the email
        // address format or not
        .isEmail()
 
        // Custom message
        .withMessage('Invalid email')
 
        // Custom validation
        // Validate email in use or not
        .custom(async (email) => {
            const existingUser =
                await repo.getOneBy({ email })
                 
            if (existingUser) {
                throw new Error('Email already in use')
            }
        })
}

使用以下命令运行index.js文件:

node index.js

文件名:package.json

包.json 文件

数据库:

数据库

输出:

使用已在使用的电子邮件注册

使用已在使用的电子邮件注册时的响应

使用未使用的电子邮件注册

使用未使用的电子邮件注册时的响应

注册成功后的数据库(用未使用的邮箱注册)

注册成功后的数据库(用未使用的邮箱注册)

注意:我们在 signup.js 文件中使用了一些 Bulma 类(CSS 框架)来设计内容。