Implement a simple registration interface back-end MVC model architecture
The first step: Add a route to the app.js of the generated express framework, with the following code: VAR API = require ('./routes/api '); App.use ('/api ', API);
Step two:. Create a new api.js instantiation route in routes, with the following code: VAR Express = require (' Express '); var router = Express. Router ();
Const Usercontroller = require (".. /controller/user.js "); Router.post ("/user/register ", usercontroller.register); module.exports = router;
Step three: Refer to the business logic layer in this route (create a new controller folder under the root directory and build a user.js as the logical layer).
Where the code is as follows:
Const USERM = require (".. /model/user.js ");//reference M-layer module
Const CRYPTO = require (' crypto ');//introduction of password-compiling module
Const Reginster = (req,res) = >{
const {Name,password} = req.body;
Userm.findoneuser ({name}, (Reqult) =>{
if (result.length>0) {
Res.json ({
Ret:true,
Data:false
})
}else{
Const HASH = crypto.createhash (' sha256 ');
Hash.update (password);
Userm.saveuser ({
Name
Password:hash.digest (' hex ')
}, () =>{
Res.json ({
Ret:true,
Data:true
})
})
}
})
}
Module.exports = {
Register
}
Because the M layer is introduced in the C layer, the M layer template needs to be created first
Create a model folder in the root directory in which a user.js file is built as the modeling layer, the model layer code is as follows:
Const MONGOOSE = require (".. /utils/database.js ");//Introduction of database Links
Const USER = Mongoose.mode (' User ', {
Name:string,
Password:string
})
Const SAVEUSER = (USERINFO,SUCCCB) = >{
Const USER = new User (userInfo);
User.save (). Then (() =>{
SUCCCB ();
})
}
Const FINDONEUSER = (USERINFO,SUCCCB) =>{
User.find (UserInfo). Then (result) =>{
SUCCCB (result);
})
}
Module.exports = {
Saveuser,
Findoneuser
}
Because database links are used at the model level, reference to the custom database link module
Database link module is to create a Utils folder under the root directory, in this folder to create a database.js file,
Where the code is as follows:
var mongoose =require (' Mongoose ');//need to download Mongoose third-party module first
Mongoose.connect (' Mongodb://127.0.0.1:27017/job ', {usemongoclient:true});
Mongoose. Promise = Global. Promise;
Module.exports = Mongoose;
Today is a bit tired, the code temporarily write so much, and then perfect
Node implements a simple registration-time back-end MVC model architecture