Nodejs initial experience, using node to write a simple mailbox to verify the registration and login

Time:2021-2-19

Open the door and enter the mountain

Pre Foundation

According to the official manual, plug-ins will be used nodemail mongoose. (this paper uses mongoose to store data. If the database is not used, the content related to mongoose can be ignored.)

1. Directory structure

├──  server.js  //Service entrance
Db // database folder (can be ignored if mongoose is not used)
│  ├── model // 
│  │  └── userModel.js  //Get schema object through Mongoose
│  └──  connect.js  //Linked database
Route // route folder
│  └──  userRouter.js  //Routing interface
Tools // tools folder
│  └──  mail.js  //Email sending plug in

Nodejs initial experience, using node to write a simple mailbox to verify the registration and login

2. Detailed explanation of ideas

Necessary preparation

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

Secondly, the use of node development must have modular thinking. In fact, this article can be in a server.js Modularization is helpful to improve development efficiency and reduce maintenance cost.

2.1 entrance/ server.js

First, establish a service, link database and introduce routing

const express = require('express')
const app = express()
Const DB = require ('. / db / connect') // link database

var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use ( bodyParser.json ()) // these three behaviors are used to parse the interface and pass parameters

//Introduce routing
const userRouter = require('./router/userRouter')

app.use('/user', userRouter)


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

2.2 linked database. / db/ connect.js

The use method is the official demo (remember to install mongodb)

//Linked database

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/chenjingtest',{useNewUrlParser: true,useUnifiedTopology: true})
//Linked database
var db =  mongoose.connection  //Linked object of database
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function() {
  console.log ('Database link succeeded ')
  // we're connected!
})
2.2.1 user object module. / db / model/ userMoldel.js

Create a new shecma object
More understanding can be found in the mongoose manual

const mongoose = require('mongoose')
var Schema = mongoose.Schema
//Get schema object through Mongoose
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) // the data object is associated with the collection ('collection name', schema object)

module.exports = User

2.3 routing module. / router/ userRouter.js

const express = require('express')
const router = express.Router()
Const user = require ('// db / model / usermodel') // import
const mailSend = require('../utils/mail')

Let codes = {} // in our example, the captcha is stored in memory. Normal development can also be put into redis or database
/**
 *@ API {post} / user / reg user registration
 *@ apiname user registration
 * @apiGroup User
 *
 *@ apiparam {string} US user name
 *@ apiparam {string} PS user password
 *@ apiparam {string} code email verification code
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.post('/reg', (req, res) => {
  //Get data
  let { us, ps, code } =  req.body  //  server.js An error will be reported if there is no parsing parameter transfer tool in
  if (us && ps && code) {
    //Judge whether the verification code is OK
    If (! (codes [US] = = number (code))) {// email as user name
      return  res.send ({err: - 4, MSG: 'captcha error'})
    }
    User.find({us}).then((data) => {
      if (!data.length) {
        //The user name does not exist and can be registered
        return  User.insertMany ({us: US, PS: PS}) // register successfully and write the data to the database
      } else {
        res.send ({err: - 3, MSG: 'user name already exists'})
      }
    }).then(() => {
      res.send ({err: 0, MSG: 'registration successful'})
    }).catch(err => {
      res.send ({err: - 2, MSG: 'registration failed'})
    })
  } else {
    return  res.send ({err: - 1, MSG: 'parameter error'})
  }
  //Data processing
  //Return data
  // res.send('test ok')
})
/**
 *@ API {post} / user / login login
 *Login @ apiname
 * @apiGroup User
 *
 *@ apiparam {string} US user name
 *@ apiparam {string} PS user password
 *
 * @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: 'login succeeded'})
      } else {
        res.send ({err: - 2, MSG: 'incorrect user name or password'})
      }
    }).catch(err => {
      // res.send ({err: - 2, MSG: 'registration failed'})
      return  res.send ({err: - 1, MSG: 'internal error'})
    })
  } else {
    return  res.send ({err: - 1, MSG: 'parameter error'})
  }
})

//Send email verification code
/**
 *@ API {post} / user / login email verification code sending
 *Email verification code of @ apiname
 * @apiGroup User
 *
 *@ apiparam {string} email
 *
 * @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) // random captcha
    codes[mail] = code
    console.log(codes)
    mailSend.send(mail, code).then(() => {
      res.send ({err: 0, MSG: 'verification code sent successfully'})
    }).catch((err) => {
      res.send ({err: - 1, MSG: 'captcha send failed'})
    })
  } else {
    res.send ({err: - 1, MSG: 'parameter error'})
  }
})

module.exports = router

3. Effect

Start local database
mongod
Nodejs initial experience, using node to write a simple mailbox to verify the registration and login
Start the service
node server.js
I use the nodemon plug-in command. In fact, it’s the same as the node command. It’s just that you don’t need to restart the service when saving the code. You can directly see the effect
Nodejs initial experience, using node to write a simple mailbox to verify the registration and login
Because we didn’t write the interface, we watched it directly through postman

3.1 call captcha interface

Nodejs initial experience, using node to write a simple mailbox to verify the registration and login
Nodejs initial experience, using node to write a simple mailbox to verify the registration and login

3.2 calling registration interface

Use an incorrect captcha first
Nodejs initial experience, using node to write a simple mailbox to verify the registration and login
Then use the correct verification code received by the mailbox
Nodejs initial experience, using node to write a simple mailbox to verify the registration and login
Specifically, let’s go to the local data to view the data
Nodejs initial experience, using node to write a simple mailbox to verify the registration and login
Data entry successful!

Recommended Today

asp.net Application of regular expression

1. Balanced group / recursive matching (?’ Group ‘), which is called the corresponding content of group, and counts it on the stack;(?’- Group ‘), and count the corresponding content named group out of the stack(?!) Zero width negative look ahead assertion. Since there is no suffix expression, attempts to match always failRegular example:,{0,1}”5″:\[[^\[\]]*(((?’Open’\[)[^\[\]]*)+((?’-Open’\])[^\[\]]*)+)*(?(Open)(?!))\],{0,1} Test […]