技術員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機純凈版,64位旗艦版,綠色軟件,免費軟件下載基地!

當前位置:主頁 > 教程 > 服務器類 >

nodejs個人博客載入頁面開發(fā)教程

來源:技術員聯(lián)盟┆發(fā)布時間:2017-10-30 00:58┆點擊:

  使用ejs作為我們博客的前端模板引擎,用來從json數(shù)據(jù)生成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('http://www.3lian.com/',function(req,res,next){

  /*渲染模板*/

  res.render("home/index");

  });

  module.exports=router;

  此時會加載/view/home/index.html模板文件,瀏覽器里正常輸出

  鏈接數(shù)據(jù)庫

  入口文件index.js

  /*鏈接數(shù)據(jù)庫*/

  global.db=require("./model/db").getInstances();

  數(shù)據(jù)庫模型文件/model/db.js

  /**

  * 數(shù)據(jù)庫操作類

  */

  var db={

  /*數(shù)據(jù)庫對象*/

  db:null,

  /*構造函數(shù)*/

  getInstances:function(){

  this.connectDatabase();

  return this;

  },

  /*鏈接數(shù)據(jù)庫*/

  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;