1: Current Environment
[Email protected]:~$ node--version && express-v && Mongo--versionv0. 12.2 4.9. 0 2.4. 9 [email protected]:
2: New Project Catalog
[Email protected]:express-test$ Express demo01[email protected]:expressInstall
Download Bootstrap using Bower:
Install Bootstrap
To add MongoDB dependency in Package.json:
{ "name": "Demo01" , "version": " 0.0.0 " "private": true , "scripts" " start ":" Node./bin/www " }, "dependencies" " Express ":" ~4.9.0 " "Body-parser": "~1.8.1" " Cookie-parser ":" ~1.3.3 ", "Morgan": "~1.3.0" " Serve-favicon ":" ~2.1.3 " "Debug": "~2.0.0" " Jade ":" ~1.6.0 " MongoDB: "~2.0.33" " Monk ":" ~1.0.1 "
Execute again: NPM install
3: Engineering Code structure
(1) App.js
//Load Dependent LibrariesvarExpress = require (' Express ');varPath = require (' path ');varFavicon = require (' Serve-favicon '));varLogger = require (' Morgan ');varCookieparser = require (' Cookie-parser '));varBodyparser = require (' Body-parser '));//MongoDB config//var mongo = require (' MongoDB ');varMonk = require (' Monk '));vardb = Monk (' Localhost:27017/test ');//Load Routing ControlvarRoutes = require ('./routes/index '));varUsers = require ('./routes/users '));//Create a Project instancevarApp =Express ();//define the Jade template engine and template file LocationsApp.set (' Views ', Path.join (__dirname), ' views ')); App.set (' View engine ', ' Jade ');//Define site Icons//App.use (Favicon (__dirname + '/public/favicon.ico '));//defining logs and output levelsApp.use (Logger (' dev ')));//Defining data parsersApp.use (Bodyparser.json ()); App.use (bodyparser.urlencoded ({extended:false }));//Defining a Cookie parserApp.use (Cookieparser ());//define a static file directoryApp.use (Express.static (Path.join (__dirname, ' public ')));//Let DB Access routingApp.use (function(req,res,next) {req.db=DB; Next ();});//matching paths and routesApp.use ('/', routes); App.use ('/user ', users);//404 error handlingApp.use (function(req, res, next) {varErr =NewError (' Not Found '); Err.status= 404; Next (err);});//development environment, 500 error handling and error stack tracingif(App.get (' env ') = = = ' Development ') {App.use (function(Err, req, res, next) {Res.status (Err.status|| 500); Res.render (' Error ', {message:err.message, error:err}); });}//production environment, 500 error handlingApp.use (function(Err, req, res, next) {Res.status (Err.status|| 500); Res.render (' Error '{message:err.message, error: {}}) ;//Output Model AppModule.exports = app;
(2) Routing users.js
varExpress = require (' Express ');varRouter =Express. Router ();/** * User list * Http://127.0.0.1:3000/user/list*/Router.get ('/list ',function(req, res) {vardb =req.db; Db.get (' user '). Find ({},{},function(err,docs) {if(Err) {ErrHandler (res,err); }Else{Res.render (' Users/list ', {title:' User list ', Userlist:docs}); } });});/** * Add New user interface * Http://127.0.0.1:3000/user/add*/Router.get ('/add ',function(req, res) {Res.render (' Users/add ');});/** * Modify user Information interface*/Router.get ('/edit/:id ',function(req,res) {vardb =req.db; Db.get (' user '). FindOne ({_id:req.params.id},{},function(err,doc) {if(Err) {ErrHandler (res,err); }Else{Res.render (' Users/edit ', {user:doc}); } });});/** * Modify user Information*/Router.post ('/update ',function(req,res) {vardb =req.db; var_id =req.body._id; varName =Req.body.name; varemail =Req.body.email; Db.get (' User '). Updatebyid (_id, {' Name ': name, ' email ': email},function(err,doc) {if(Err) {ErrHandler (res,err); }Else{res.redirect (' List '); } });});/** * Save newly added user information*/Router.post ('/save ',function(req,res) {vardb =req.db; varName =Req.body.name; varemail =Req.body.email; Db.get (' User '). Insert ({' Name ': Name,' Email ': email},function(err,doc) {if(Err) {ErrHandler (res,err); }Else{res.redirect (' List '); } } );});/** * Delete according to _id*/Router.get ('/delete/:id ',function(req,res) {vardb =req.db; Db.get (' user '). Remove ({_id:req.params.id},function(err,doc) {if(Err) {ErrHandler (res,err); }Else{Res.render (' Info ', {info: ' Delete succeeded! ', url: ' Http://127.0.0.1:3000/user/list '}); } });});/** * ERROR Handling * @param res * @param err*/functionErrHandler (res,err) {res.status (Err.status|| 500); Res.render (' Error ', {message:err.message, error:err});}; Module.exports= Router;
(3) Users/list.jade
Extends. /layoutblock content div.container h3.text-center.text-primary user list hr A.BTN.BTN-PRIMARY.BTN-SM ( href= ' Add ') adds table.table.table-bordered.table-condensed.table-hover thead tr.bg-info Th.text-center.col-xs-4 User name th.text-center.col-xs-5 mailbox th.text-center.col-xs-3 operations tbody each User, I in userlist tr.text-center td= user.name td= user.email TD A.btn.btn-danger.btn-sm.margin-left (href= ' delete/' +user._id) Delete a.btn.btn-warning.btn-sm.margin-left (href= ' edit/' +user._id) modified
(4) Users/add.jade
Extends. /layoutblock content div.container h3.text-center.text-primary Add user hr form (name= "Adduserform", Method= "POST", action= "/user/save") div.form-group label (for= ' name ') Username Input#name.form-control ( Name= ' name ', placeholder= ' user name ') div.form-group label (for= ' email ') Mailbox Input#email.form-control (name= ' Email ', type= ' email ', placeholder= ' email address ') div.text-center button.btn.btn-primary.margin-right (type= ' Submit ') Save button.btn.btn-default.margin-left (type= ' reset ') reset
(5) Users/edit.jade
Extends. /layoutblock content Div.container h3.text-center.text-primary Modify user information hr form (name= "Edituserform ", method=" post ", action="/user/update ") input (type= ' hidden ', name= ' _id ', value=user._id) Div.form-group label (for= ' name ') Username input#name.form-control (name= ' name ', placeholder= ' user name ', value=user.name) Div.form-group label (for= ' email ') Mailbox input#email.form-control (name= ' email ', type= ' email ', placeholder= ' Email address ', value=user.email) div.text-center button.btn.btn-primary.margin-right (type= ' submit ') Save Button.btn.btn-default.margin-left (type= ' reset ') reset
(6) Info.jade
Extends Layoutblock content div.container.text-center h1.text-warning=info a.btn.btn-primary (href =url) return
Express+jade+bootstrap+mongdb Simple CRUD Test