Error handling Middleware
Define error handling middleware must use 4 parameters, otherwise it will be used as normal middleware
/* Error Handler */ application.use (function(err,req,res,next) { console.error (err.stack); Res.status. Send ("Code error, error message:<br/>" +Err.stack);}); /* 404 */ application.use (function(req,res,next) { res.status (404). Send (" 404 pages were dug away by Martians ") ;
Create a file structure
Public folders (common), Controller folders (controllers), model folders (models), view folders (views), Static resource folders (statics)
Define configuration files and function files and load
Configuration file Common/config.js
/* * * Public configuration file */ module.exports={ db_host:' localhost ', db_name:' blog ', db_user: ' Root ', db_pass:' root ', db_pre:', app_port:' 8888 '};
function File Common/functions.js
/** * Public Function file*/Module.exports={ /*Simulate PHP's date () function*/phpdate:function(formatstr,time) {varParammodel= ' Ymdhis '; if(!FORMATSTR) formatstr= "y-m-d h:i:s"; if(time) {Mydatetime=NewDate (time*1000); }Else{mydatetime=NewDate (); } varStrtimearr=[Mydatetime.getfullyear (). ToString (), (Mydatetime.getmonth ()+1). ToString (), Mydatetime.getdate (). ToString (), Mydatetime.gethours (). ToString (), Myda Tetime.getminutes (). ToString (), Mydatetime.getseconds (). ToString (),]; for(vari=0;i<strtimearr.length; i++) {Formatstr=Formatstr.replace (Parammodel.charat (i), strtimearr[i]); } returnFormatstr; }};
Load public files, define resource files
/* load public files, define resource files */ Global. C=require ("./common/config"); global. F=require ("./common/functions"); Application.use (express.static (' public '));
Routing-level Middleware
The controller is divided into two groups home and admin
/* routing-level middleware */ application.use ('/', require ('./controller/home/index ')); Application.use ('/admin ', require ('./ Controller/admin/index '));
[Nodejs] Nodejs Development Personal Blog (ii) entry file