Node.js笔记(一)项目的建立

1、supervisor 可以帮助你实现这个功能,它会监视你对代码的改动,并自动重启 Node.js。

   使用方法很简单,首先使用 npm 安装 supervisor:

2、app.js是工程的入口,里面负责定义路由控制器

   routes/index.js 是路由控制器文件 用于组织展示的内容

3、index.ejs 是模板文件 即routes/index.js中调用的模版

4、app.get('/hello', routes.hello);

   固定的路径设置路由规则


5、

1
2
3
app.get( '/user/:username' function (req, res) {
         res.send( 'user: '  + req.params.username);
    });

   高级的路由匹配模式

6、app.set('views', __dirname + '/views');

   app.set('view engine', 'ejs');

   模版引擎,表明要是用的模版引擎是 ejs,模版的位置在 views子目录下

   在routes/index.js的exports.index函数中通过语句来调用模版引擎:

   res.render('index', {title: 'Express'})

   res.render的作用就是调用模版引擎,并将结果返回给浏览器客户端,它接受的两个参数

   第一个参数是模版的名称,第二个参数是模版里面要转换过来的数据,用与模版翻译


   ejs的标签系统只有三种:<% code %>  表示javascript代码,

 <%= code %> 显示转换过HTML特殊字符的内容

 <%- code %> 显示原始HEML内容

7、layout.ejs  是一个网页布局模版,一般页眉页脚等重复比较多的会在这个模版里面来写,

               也可以关闭模版功能,

      在app.js中app.configure中layout: false

               另一种情况就是,一个项目可能有多个网页布局模版,前台或者后台,

      也可以在模版翻译的时候制定布局模版

       res.render('userlist', {

title: '用户列表后台管理系统',

layout: 'admin'

});

8、从 http://twitter.github.com/bootstrap/下载 Twitter Bootstrap

   从 http://jquery.com/ 下载一份最新版的 jquery.js


-------------------------------------------------------------------------------------------

////////////////////////////Node.js建立项目////////////////////////////////////////////////

-------------------------------------------------------------------------------------------

1、安装Express框架,

1
2
$ npm install -g express   //全局安装
$ npm install -g express -generator  //这段命令可别忘了,不然会提示“express命令找不

到的”

2、创建工程

1
express -e microblog  //即ejs,-j(即jade)(Express 4.0出来之后老的命令改变了)

3、创建依赖

1
2
cd  microblog  //microblog 为前面创建工程的文件夹
npm  install

4、启动项目

1
npm start

wKioL1Yp00KjUIs7AAC6lfV_19g068.jpg


5、关闭服务器 连着按两个Ctrl + C。


项目的入口文件 app.js


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var  express = require( 'express' );
var  path = require( 'path' );
var  favicon = require( 'serve-favicon' );
var  logger = require( 'morgan' );
var  cookieParser = require( 'cookie-parser' );
var  bodyParser = require( 'body-parser' );
 
var  routes = require( './routes/index' );
var  users = require( './routes/users' );
 
var  app = express();
 
// view engine setup
app.set( 'views' , path.join(__dirname,  'views' ));
app.set( 'view engine' 'ejs' );
 
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger( 'dev' ));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:  false  }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname,  'public' )));
 
app.use( '/' , routes);
app.use( '/users' , users);
 
// catch 404 and forward to error handler
app.use( function (req, res, next) {
   var  err =  new  Error( 'Not Found' );
   err.status = 404;
   next(err);
});
 
// error handlers
 
// development error handler
// will print stacktrace
if  (app.get( 'env' ) ===  'development' ) {
   app.use( function (err, req, res, next) {
     res.status(err.status || 500);
     res.render( 'error' , {
       message: err.message,
       error: err
     });
   });
}
 
// production error handler
// no stacktraces leaked to user
app.use( function (err, req, res, next) {
   res.status(err.status || 500);
   res.render( 'error' , {
     message: err.message,
     error: {}
   });
});
 
 
module.exports = app;


6、app.set是Express的参数设置工具,接受一个键(Key)一个值(Value)

可用参数如下:

  1. basepath:基础地址,通常用于res.redirect()跳转

  2. views:视图文件目录,存放模版文件

  3. view engine:视图模版引擎

  4. view options:全局视图参数对象

  5. view catch : 启用视图缓存

  6. case sensitive routes:路径是否区分大小写

  7. strict routing:严格路径,启用后不会忽略路径末尾的 "/"

  8. jsonp callback:开启透明的jsonp支持

7、Express依赖与connect,提供了大量的中间件,用app.use来启用。

bodyParser的功能是解析客户端请求,通常是通过POST传送的内容。


8、

1
2
app.use( '/' , routes);
app.use( '/users' , users);


是一个路由控制器,如果请求是访问"/"路径,则会转到'./routes/index'来控制。


9、app.listen(3000); 启动,监听3000端口。该app.js中没有写到,会默认端口为3000

在 /bin/ 目录下的文件 "www" 中,


1
2
3
4
5
6
7
8
9
10
11
12
/**
  * Get port from environment and store in Express.
  */
var  port = normalizePort(process.env.PORT ||  '3000' );
app.set( 'port' , port);
.
.
.
/**
  * Listen on provided port, on all network interfaces.
  */
server.listen(port);

10、 routes/index.js是路由文件,相当于控制器,


1
2
3
4
5
6
7
var  express = require( 'express' );
var  router = express.Router();
/* GET home page. */
router.get( '/' function (req, res, next) {
   res.render( 'index' , { title:  'Express'  });
});
module.exports = router;


11、index.ejs 是模板文件,即 routes/index.js 中调用的模板。内容是:

1
2
< h1 ><%= title %></ h1 >
< p >Welcome to <%= title %></ p >

12、layout.ejs

默认情况下所有的模板都继承自 layout.ejs,即 <%- body %>

部分才是独特的内容,其他部分是共有的,可以看作是页面框架。


13、 app.js 中并没有一个路由规则指派到 /stylesheets/style.css,但 app 通过

app.use(express.static(path.join(__dirname, 'public'))); 配置了静态文件服务器,因此

/stylesheets/style.css 会定向到 app.js 所在目录的子目录中的文件 public/stylesheets/style.css,


14、重新写一个Hello控制器

1)在app.js里面添加:

1
app.use( '/hello' , routes);

2)在index.js里面添加

1
2
3
router.get( '/hello' function (req, res, next) {
   res.send( 'The time is '  new  Date().toString());
});

这两个文件相互照应着。页面就出来了

wKiom1Yp5LGwN5VBAACQPVyami8244.jpg


发布了14 篇原创文章 · 获赞 17 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/liu305088020/article/details/49362433