Mongoose of Node (ten) cooperates with Node routing to realize mailbox registration and login (Post version)

Mongoose of Node (ten) cooperates with Node routing to realize mailbox registration and login (Post version)

First create a new HTML: (import jq)

<!DOCTYPE html > < html lang = "en" > < head > < meta charset = "UTF-8"/> < meta name = "viewport" content = "width=device-width, initial-scale=1.0"/> < meta http-equiv = "X-UA-Compatible " content = "ie=edge"/> < title > Document </title > < script src = "./jquery.js" > </script > <style > * { margin : 0 ; padding : 0 ; } div :nth-child ( 3 ) { display : none; } input { display : block; height : 40px ; width : 200px ; margin : 20px auto; } Button : Not ( #email ) { the display : Block; height : 30px ; width : 70px ; background : LightCoral; border : none; margin : 0 Auto; } #email { display : block; height : 30px ; width : 100px ; margin : 0 auto; } ul { height : 50px ; width : 200px ; background : lightblue; margin : 0 auto; list-style : none; } li { height : 50px ; width : 100px ; float : left; text-align : center; line-height : 50px ; } li :hover { background : lightgreen; cursor : pointer; } </style > </head > < body > < ul > < li id = "regChange" > Register </li > < li id = "loginChange" > Login </li > </ul > < div id = "reg" > < input type = "text " placeholder = "Mailbox" id = "user"/> <input type = "text" placeholder ="Password" id = "psd"/> < input type = "text" placeholder = "Verification code" id = "sendmail"/> < button id = "email" > Send verification code </button > < button id = " btn" > Register </button > </div > < div id = "login" > <input type = "text" placeholder= "Username" id = "loguser"/> < input type = "text" placeholder = "Password" id = "logpsd"/> < button id = "logbtn" > Login </button > </div > < script > //Add a listener event btn.addEventListener( "click" , clickHandler); logbtn.addEventListener( "click" , clickHandler); email.addEventListener( "click" , sendHandler); regChange.addEventListener( "click" , changeHandler); loginChange.addEventListener( "click" , changeHandler); function clickHandler ( e ) { if ( this .textContent === "register" ) { //If it is empty, pop out if (!user.value || !psd.value || !sendmail.value) { alrt( "cannot be empty" ); return ; } //Click to send the email number, password and verification code to the backend when you click on the registration $.post( "http://localhost:1024/main/reg" , { email : user.value, password : psd.value, mailnum : sendmail .value }, function ( res ) { //The object returned in the background, if hasUser is true, it means there is a user name, otherwise the registration is successful if (res.hasUser) { alrt( "Registration failed" ); return ; } else { alrt( "Registered successfully~" ); } //Hide registration after success, display login reg.style.display = "none" ; login.style.display = "block" ; } ); } else if ( this .textContent === "Login" ) { //Same as registration, cannot be empty if (!loguser.value || !logpsd.value) { alrt( "cannot be empty" ); return ; } //Click to send the email number and password to the background when logging in $.post( "http://localhost:1024/main/login" , { email : loguser.value, password : logpsd.value }, function ( res ) { //The object returned in the background, if isUser is true, the description is correct, and jump to the welcome page, otherwise it fails if (res.isUser) { alrt( "Login successful" ); location.href = "./welcome.html" ; } else { alrt( "Username or password is incorrect" ); return ; } } ); } } function sendHandler ( e ) { //Click to get the verification code and send the verification code to the backend for comparison $.post( "http://localhost:1024/main/sendmail" , { email : user.value }); } function changeHandler ( e ) { //Click the register above to switch to login if (e.target.textContent === "register" ) { reg.style.display = "block" ; login.style.display = "none" ; } else { reg.style.display = "none" ; login.style.display = "block" ; } } </script > </body > </html > Copy code

Create a new set folder and create several js files in the folder:

main.js (connect to mongoose database)

const mongoose = require ( 'mongoose' ); //Introduce mongoose mongoose.connect( 'mongodb://localhost:27017/UserList' , { useNewUrlParser : true }); //Connect to the database let db = mongoose.connection; db.on( "error" , function ( error ) { console .log( "error:" + error); }); db.on( "open" , function () { console .log( "Connected successfully" ); }); db.on( 'disconnected' , function () { console .log( 'Disconnected' ); }); Module1 .exports = Mongoose; //Throws mongose objects duplicated code

mod.js (Instantiate Schema, create a new database)

const mongoose = require ( './main' ); //Introduce the main module const Schema = mongoose.Schema; //Create a new schema object let userSchema = new Schema({ email : { type : String , required : true }, password : { type : String , required : true } }); //instantiate an object of the let usermodel = mongoose.model ( 'alluser' , userSchema); //create a new database Module1 .exports = usermodel; //Throws module duplicated code

send.js (email sending module)

const nodemailer = require ( "nodemailer" ); let obj = { transporter : nodemailer.createTransport({ service : "qq" , //operator qq mailbox Netease// port : 465 , secure : true , auth : { user : " *******@qq.com" , //Sender s email pass : "********" //pop3 authorization code } }), send : function ( mail, content,callback ) { mailOptions = { from : '"Hello World~" <******@qq.com>' , to : mail, subject : content, text : content, html : "<h1>" + content + "</h1>" }; this .transporter.sendMail(mailOptions, ( error, info ) => { if (error) { return console .log(error); } console .log( "Message sent: %s" , info.messageId); callback(); }); } }; module .exports = obj; copy the code

reg.js (create registration module)

const express = require ( 'express' ); const router = express.Router(); //New route const Model = require ( './mod' ); //Incoming database object const sendMail = require ( './send ' ); //Module object sent by incoming mail var count = "" ; //Create a new empty character to store the verification code, which can be called globally //Use the post method to transmit data router.post( '/reg' , ( req , res ) => { //Save the data from the front end var mail = req.body.email; varpsd = req.body.password; var mailnum = req.body.mailnum; //Use the Model object to connect to the database Model.find({ //Query the mailbox'email ' : mail }).then( ( data ) => { //If the returned mailbox is found or the verification code is incorrect, an error will be thrown if (data.length >= 1 || mailnum !== count) { res.send({ hasUser : true }); return ; } res.send({ hasUser : false }) Model.insertMany({ //On the contrary, insert the mailbox into the database'email ' : mail, 'password' : psd }).then( ( result ) => { console .log(result); }) }).catch( ( err ) => { console .log(err); }); }); //Mailbox verification interface router.post( "/sendmail" , ( req, res ) => { count = "" ; //Initialize the verification code container var mail = req.body.email; //Get the mailbox number from the front end for ( let i = 0 ; i < 4 ; i++) { count += Math .floor( Math .random() * 10 ); //Generate 4 random numbers } var callback = () => { console .log( "Send successfully" ); }; sendMail.send(mail, count, callback); //Call the mail sending module res.send( 'send' ); }); module .exports = router; copy the code

login.js (login module)

const express = require ( 'express' ); const router = express.Router(); //Create a new route const Model = require ( './mod' ); //Get database objects router.post( '/login' , ( req, res ) => { //Routing address //Save the data from the front end var mail = req.body.email; var psd = req.body.password; Model.find({ //Query whether there is the user, if the user's mailbox and password match, the correct is thrown, otherwise the error object'email' : mail, 'password' : psd will be thrown }).then( ( data ) => { if (data.length >= 1 ) { res.send({ isUser : true }); } else { res.send({ isUser : false }); } }).catch( ( err ) => { console .log(err); }); }); module .exports = router; copy the code

Then create a new service (server.js) outside the set folder, and splice all the modules:

const express = require ( 'express' ); const app = express(); const cors = require ( "cors" ); //Introduce cors module (solve cross-domain issues) var bodyParser = require ( 'body-parser' ); app.use(cors()); //The following header file is similar to http request (another article has written about http request, which is also registration and login) app.all( "*" , function ( req, res, next ) { //Set to allow cross-domain Domain name, * stands for allowing any domain name to cross domain res.header( "Access-Control-Allow-Origin" , "*" ); res.header( "Access-Control-Allow-Headers" , "content-type" ); //Allowed header type res.header( "Access-Control-Allow-Methods" , "DELETE,PUT,POST,GET, OPTIONS" ); //Available cross-domain request method next(); //Whether to continue downward execution }); //Solve the data format problem of post transmission app.use(bodyParser.urlencoded({ extended : false })) app.use(bodyParser.json()) //Route selection import registration const reg = require ( '../set/reg.js' ); app.use( '/main' , reg); //Route selection import login const login = require ( '../set/login.js' ); app.use( '/main' , login); //enable monitoring app.listen( 1024 , () => { console .log( 'Server Start~' ); }); Copy code

Finally, run server.js to achieve registration and login

Note: The case needs to use monogoDB, Jq, mongoose module, express module, nodemailer module, cors module, body-parser module