天天看点

ExpressJS入门指南(二)ExpressJS入门指南(二)

版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。 https://blog.csdn.net/chszs/article/details/8872553

ExpressJS入门指南(二)

作者:chszs,转载需注明。博客主页:

http://blog.csdn.net/chszs

紧接前一篇《

ExpressJS入门指南

六、使用express(1)产生应用

Express框架绑定了一个可执行脚本,名为express(1)。如果使用npm对Express框架进行全局安装,那么express到处都能使用。

> npm install -g express

express(1)工具提供了简单的产生应用程序骨架的方式,而且它有一定的使用范围。比如它只支持有限的几个模板引擎,而Express自身是支持任意Node构建的模板引擎。可以使用下面的命令进行查看:

> express --help

PS D:\tmp\node\hello-world> express --help

  Usage: express [options]

  Options:

    -h, --help          output usage information

    -V, --version       output the version number

    -s, --sessions      add session support

    -e, --ejs           add ejs engine support (defaults to jade)

    -J, --jshtml        add jshtml engine support (defaults to jade)

    -H, --hogan         add hogan.js engine support

    -c, --css <engine>  add stylesheet <engine> support (less|stylus) (defaults to plain css)

    -f, --force         force on non-empty directory

如果想生成支持EJS、Stylus、和会话Session的应用,那么该这样做:

> express --sessions --css stylus --ejs myapp

D:\tmp\node\hello-world>express --sessions --css stylus --ejs myapp

   create : myapp

   create : myapp/package.json

   create : myapp/app.js

   create : myapp/public

   create : myapp/public/javascripts

   create : myapp/public/images

   create : myapp/public/stylesheets

   create : myapp/public/stylesheets/style.styl

   create : myapp/routes

   create : myapp/routes/index.js

   create : myapp/routes/user.js

   create : myapp/views

   create : myapp/views/index.ejs

   install dependencies:

     $ cd myapp && npm install

   run the app:

     $ node app

与其它Node应用一样,必须安装依赖包。

> cd myapp

> npm install

然后运行myapp,执行:

> node myapp.js

使用浏览器访问地址:http://localhost:3000/

可以看到:

Express

Welcome to Express

这就是创建简单应用的全过程。要记住,Express框架并没有绑定任何指定的目录结构,

七、Express框架说明

Express框架是Node.js第三方框架中比较好的Web开发框架。Express除了为HTTP模块提供了更高层的接口外,还实现了很多功能,其中包括:

1)路由控制;

2)模板解析支持;

3)动态视图;

4)用户会话;

5)CSRF保护;

6)静态文件服务;

7)错误控制器;

8)访问日志;

9)缓存;

10)插件支持。

要说明一点,Express并不是无所不包的全能框架(像Rails或Django那样实现了模板引擎甚至是ORM),它只是一个轻量级的Web框架,其主要功能只是对HTTP协议中常用操作的封装,更多的功能需要插件或整合其它模块来完成。

比如:

var express = require('express');

var app = express();
app.use(express.bodyParser());
app.all('/', function(req, res){
	res.send(req.body.title + req.body.text);
});
app.listen(3000);