nodejs初体验,使用node写一个简易邮箱验证注册登陆

开门进山html

前置基础

根据官方手册,会使用插件 nodemail mongoose。(本文使用了mongoose,用来存数据。若没用到数据库,可忽略与mongoose相关的内容)node

1.目录结构

├── server.js // 服务入口
├── db // 数据库文件夹(没使用mongoose能够忽略)
│  ├── model // 
│  │  └──userModel.js // 经过mongoose得到schema对象
│  └── connect.js // 连接数据库
├── router // 路由文件夹
│  └── userRouter.js // 路由接口
├── utils // 工具文件夹
│  └── mail.js // 邮件发送插件

image.png

2.思路详解

必要准备redis

  1. npm init --yes
  2. npm i express
  3. npm i nodemailer

其次使用node开发必定要有模块思想。其实本文能够在一个server.js中完成,模块化处理有利于提升开发效率和下降维护成本。mongodb

2.1 入口 ./server.js

首先 创建一个服务,连接数据库,引入路由数据库

const express = require('express')
const app = express()
const db = require('./db/connect') // 连接数据库

var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json()) // 这三行为解析接口传参

// 引入路由
const userRouter = require('./router/userRouter')

app.use('/user', userRouter)


app.listen(3000, ()=> {
  console.log('server start')
})

2.2 连接数据库 ./db/connect.js

使用方法就是官方demo (系统记得安装MongoDB)express

// 连接数据库

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/chenjingtest',{useNewUrlParser: true,useUnifiedTopology: true})
// 连接数据库
var db = mongoose.connection // 数据库的连接对象
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function() {
  console.log('数据库连接成功')
  // we're connected!
})
2.2.1 用户对象模块./db/model/userMoldel.js

新建一个shecma对象
更多理解能够移步mongoose手册npm

const mongoose = require('mongoose')
var Schema = mongoose.Schema
// 经过mongoose得到schema对象
var userSchema = new Schema({
  us: { type: String, required: true },
  ps: { type: String, required: true },
  age: Number,
  sex: { type: Number, default: 0 }
})

var User = mongoose.model('user', userSchema) // 该数据对象和集合关联('集合名', schema对象)

module.exports = User

2.3 路由模块./router/userRouter.js

const express = require('express')
const router = express.Router()
const User = require('../db/model/userModel') // 引入
const mailSend = require('../utils/mail')

let codes = {} // 咱们这个例子 验证码就放着内存中了。正常开发也能够放redis 或者 数据库内
/**
 * @api {post} /user/reg 用户注册
 * @apiName 用户注册
 * @apiGroup User
 *
 * @apiParam {String} us 用户名
 * @apiParam {String} ps 用户密码
 * @apiParam {String} code 邮箱验证码
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.post('/reg', (req, res) => {
  // 获取数据
  let { us, ps, code } = req.body // server.js中没有解析传参工具的话 会报错
  if (us && ps && code) {
    // 判断验证码是否ok
    if (!(codes[us] === Number(code))) { // 邮箱做为用户名
      return res.send({err: -4, msg: '验证码错误'})
    }
    User.find({us}).then((data) => {
      if (!data.length) {
        // 用户名不存在 能够注册
        return User.insertMany({ us: us, ps: ps}) // 注册成功 将数据写入数据库
      } else {
        res.send({err: -3, msg: '用户名已存在'})
      }
    }).then(() => {
      res.send({ err: 0, msg: '注册成功'})
    }).catch(err => {
      res.send({ err: -2, msg: '注册失败'})
    })
  } else {
    return res.send({err: -1, msg: '参数错误'})
  }
  // 数据处理
  // 返回数据
  // res.send('test ok')
})
/**
 * @api {post} /user/login 登陆
 * @apiName 登陆
 * @apiGroup User
 *
 * @apiParam {String} us 用户名
 * @apiParam {String} ps 用户密码
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.post('/login', (req, res) => {
  console.log(req.body)
  let { us, ps } = req.body
  console.log(us, ps)
  if (us && ps) {
    // 
    User.find({ us, ps }).then((data) => {
      if (data.length > 0) {
        res.send({err: 0, msg: '登陆成功'})
      } else {
        res.send({err: -2, msg: '用户名或者密码不正确'})
      }
    }).catch(err => {
      // res.send({ err: -2, msg: '注册失败'})
      return res.send({err: -1, msg: '内部错误'})
    })
  } else {
    return res.send({err: -1, msg: '参数错误'})
  }
})

// 发送邮件验证码
/**
 * @api {post} /user/login 邮箱验证码发送
 * @apiName 邮箱验证码发送
 * @apiGroup User
 *
 * @apiParam {String} mail 邮箱
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.post('/getMailCode', (req, res) => {
  let { mail } = req.body
  if (mail) {
    let code = parseInt( Math.random() * 10000 ) // 随机验证码
    codes[mail] = code
    console.log(codes)
    mailSend.send(mail, code).then(() => {
      res.send({err: 0, msg: '验证码发送成功'})
    }).catch((err) => {
      res.send({err: -1, msg: '验证码发送失败'})
    })
  } else {
    res.send({err: -1, msg: '参数错误'})
  }
})

module.exports = router

3.效果

启动本地数据库
mongod
image.png
启动服务
node server.js
我使用的是nodemon插件命令,其实就是node命令同样的,只是能够在保存代码的时候 不用重启服务,能够直接看效果
image.png
由于咱们没写界面,直接经过postman看json

3.1调用验证码接口

image.png
image.png

3.2调用注册接口

先用一个错误的验证码
image.png
再使用邮箱接收的正确验证码
image.png
具体咱们进到本地数据查看数据
image.png
数据录入成功!api

相关文章
相关标签/搜索