nodejs个人博客开发第三步 载入页面

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

nodejs个人博客开发第三步 载入页面

陶士涵   2020-05-15 我要评论

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

模板引擎

使用ejs作为我们博客的前端模板引擎,用来从json数据生成html字符串

安装:npm install ejs -save

使用:入口文件中写入下面代码,定义/view/目录为视图目录

/*模板引擎*/ 
application.set('views',__dirname+'/views');
application.engine('.html',require("ejs").__express);
application.set('view engine','html');

首页路由控制器

/**
* 首页控制器
*/
var router=express.Router();
router.get('/',function(req,res,next){
  /*渲染模板*/
  res.render("home/index");
});
module.exports=router;

此时会加载/view/home/index.html模板文件,浏览器里正常输出

链接数据库

入口文件index.js

/*链接数据库*/ 
global.db=require("./modelhttps://img.qb5200.com/download-x/db").getInstances();

数据库模型文件/modelhttps://img.qb5200.com/download-x/db.js

/**
* 数据库操作类
*/
var db={
  /*数据库对象*/
  db:null,
  /*构造函数*/
  getInstances:function(){
    this.connectDatabase();
    return this;
  },
  /*链接数据库*/
  connectDatabase:function(){
    var mysql=require('mysql');
    var db=mysql.createConnection({
      host:C.DB_HOST,
      user:C.DB_USER,
      password:C.DB_PASS,
      database:C.DB_NAME
    });
    db.connect();
    this.db=db;
    this.C=C;
  },
  select:function(tableName,callback,where,field){
    field=field ? field : '*';
    var sql="select "+field+" from "+this.C.DB_PRE+tableName;
    if(where){
      sql+=" where "+where;
    }
    this.db.query(sql,callback);
  }
}
module.exports=db;

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们