NodeJs学习笔记

因为Express3.0以上的版本不支持layout了,所以,NodeJs开发指南的blog代码不能用,但是可以通过下面的方法实现

npm install express-partials

partials=require('express-partials');
app.use(partials());

 

这样就可以使用layout了

详细代码如下
app.js
-------------------------------------------------------

/**
* Module dependencies.
*/
 
var express =require('express')
  , routes =require('./routes')
  , user =require('./routes/user')
  , http =require('http')
  ,partials =require('express-partials')
  , path =require('path');
 
var app = express();
 
app.configure(function(){
  app.set('port', process.env.PORT ||3000);
  app.set('views', __dirname +'/views');
  app.set('view engine','ejs');
  app.use(partials());
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());
  app.use(app.router);
  app.use(express.static(path.join(__dirname,'public')));
});
 
app.configure('development',function(){
  app.use(express.errorHandler());
});
/*
开始微博网站的制作。
路由部分
*/
app.get("/",routes.index);
app.get("/u/:user",routes.user);
app.post("/post",routes.post);
app.get("/reg",routes.reg);
app.post("/reg",routes.doReg);
app.get("/login",routes.login);
app.post("/login",routes.doLogin);
app.get("/logout",routes.logout);
/*
路由结束
*/
http.createServer(app).listen(app.get('port'),function(){
  console.log("Express server listening on port "+ app.get('port'));
});


---------------------------------------------------------------------------------
routes/index.js
--------------------------------------------------------------------------------

 
/*
* GET home page.
*/
 
exports.index =function(req, res){
  res.render('index.ejs',{ title:'Express'});
};
exports.hello =function(req,res){
    res.send("this time is"+newDate().toString());
}
//微博路由开启
exports.user=function(req,res){
};
exports.post=function(req,res){
};
exports.reg=function(req,res){
};
exports.doReg=function(req,res){
};
exports.login=function(req,res){
};
exports.doLogin=function(req,res){
};
exports.logout=function(req,res){
};
//微博路由结束


--------------------------------------------------------------
views/layout.ejs
--------------------------------------------------------------

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <linkrel='stylesheet'href='/stylesheets/style.css'/>
  </head>
  <body>
    <%- body %>
  </body>
</html>


---------------------------------------------------------------
views/index.ejs
---------------------------------------------------------------

  <h1><%= title %></h1>
    <p>Welcome to <%= title %> this is a test</p>

posted on 2013-06-28 13:48  coolnet  阅读(356)  评论(0编辑  收藏  举报

导航