当前位置: 移动技术网 > IT编程>开发语言>JavaScript > nodejs个人博客开发第二步 入口文件

nodejs个人博客开发第二步 入口文件

2018年05月21日  | 移动技术网IT编程  | 我要评论

本文为大家分享了nodejs个人博客开发的入口文件,具体内容如下

错误处理中间件

定义错误处理中间件必须使用4个参数,否则会被作为普通中间件

/*错误处理器*/
application.use(function(err,req,res,next){
 console.error(err.stack);
 res.status(500).send("代码出错了,错误信息:<br/>"+err.stack);
});
/*404*/
application.use(function(req,res,next){
 res.status(404).send("404页面被火星人挖走了");
});

创建文件结构

公共文件夹(common),控制器文件夹(controller),模型文件夹(model),视图文件夹(view),静态资源文件夹(static)

定义配置文件和函数文件并载入

配置文件common/config.js

/**
* 公共配置文件
*/
module.exports={
 db_host:'localhost',
 db_name:'blog',
 db_user:'root',
 db_pass:'root',
 db_pre:'',
 app_port:'8888'
};

函数文件common/functions.js

/**
* 公共函数文件
*/
module.exports={
 /*模拟php的date()函数*/
 phpdate:function(formatstr,time){
  var parammodel='ymdhis';
  if(!formatstr) formatstr="y-m-d h:i:s";
  
  if(time){
   mydatetime=new date(time*1000);
  }else{
   mydatetime=new date();
  }
  var strtimearr=[
   mydatetime.getfullyear().tostring(),
   (mydatetime.getmonth()+1).tostring(),
   mydatetime.getdate().tostring(),
   mydatetime.gethours().tostring(),
   mydatetime.getminutes().tostring(),
   mydatetime.getseconds().tostring(),
  ];
  for(var i=0;i<strtimearr.length; i++){
   formatstr=formatstr.replace(parammodel.charat(i), strtimearr[i]);     
  }
  return formatstr;
 }

};

载入公共文件,定义资源文件

/*载入公共文件,定义资源文件*/
global.c=require("./common/config");
global.f=require("./common/functions"); 
application.use(express.static('public'));

路由级中间件

控制器分为两组home和admin

/*路由级中间件*/
application.use('/',require('./controller/home/index'));
application.use('/admin',require('./controller/admin/index'));

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网