简单运行步骤
1. 安装
/* 进入项目文件中*/
$ npm init
entry point: (app.js) /*指定项目入口文件*/
$ npm install express --save /* 下载express */
2. 编写入口文件app.js
var express = require('express');
var app = express();
app.get('/',function(req,res){
res.send('hello world');
});
var server = app.listen(9000,function(){ /*监听端口*/
var host = server.address().address;
var port = server.address().port;
console.log('example app listening at http://%s:%s',host,port); /*控制台输出*/
});
3. 运行 (http://localhost:9000)
$ node app.js /*运行入口文件*/
简单语法
(1) 简单的express路由
var express = require('express');
var app = express();
/*路由,接受get,pust,delete等请求*/
app.get('/',function(req,res,next){
res.send('hello'); //响应,将hello返回给浏览器页面显示
})
app.post('/', function (req, res) {
res.send('Got a POST request');
});
app.all('/secret',function(req,res,next){
console.log('在/secret路径下,无论是什么请求,都加载中间件');
});
路由路径
(a). // 字符串路由路径 app.get('/random.text',function(req,res){ .....// 处理逻辑 }); (b). // 字符串模式路由 app.get('/ab?cd',function(req,res){ // 匹配/abcd 和/acd .... }); (c). // 正则表达式路由 app.get(/.*fly$/,function(req,res){ // 匹配以fly结尾的字符路由,如butterfly ... });
- 路由句柄
(a). //使用一个回调函数处理路由
app.get('/',function(req,res){
res.send('hello');
});
(b). // 使用多个回调函数处理路由,记得指定next对象
app.get('/',function(req,res,next){
console.log('response will be send by the next function');
next();
},function(req,res){
res.send('hello from b');
})
(c). // 使用回调函数数组处理路由
var cb0 = function (req, res, next) {
console.log('CB0');
next();
}
var cb1 = function (req, res, next) {
console.log('CB1');
next();
}
var cb2 = function (req, res) {
res.send('Hello from C!');
}
app.get('/example/c', [cb0, cb1, cb2]);
- 响应方法
res.download() // 提示下载文件
res.end() // 终结响应处理程序
res.render() // 渲染视图模板
res.send() // 发送各种类型的响应
(2) express托管静态文件
app.use('/static',express.static('public')); /*将public下的静态文件资源都托管到/static下,可以直接通过带有“/staitc”前缀的地址来访问public目录下的文件*/
例如: http://localhost:9000/static/images/logo.png 可以在浏览器直接访问该logo
(3) 渲染html文件
res.render() /*渲染html*/
res.sendFile() /*直接对外输出html文件*/
express.Router
// 写在前面
(1) 可使用app.route()创建路由路径的链式路由句柄
app.route('/book') /*路径在一个地方指定,有助于创建模块化的路由,减少代码冗余和拼写错误*/
.get(function(req, res) {
res.send('Get a random book');
})
.post(function(req, res) {
res.send('Add a book');
})
.put(function(req, res) {
res.send('Update the book');
});
express.Router类创建模块化,可挂载的路由句柄。Router实例是一个完整的中间件和路由系统.
// 在app目录下创建birds.js
var express = require('express');
var router = express.Router(); // 实例化
// 该路由使用的中间件
router.use(function timeLog(req,res,next){
console.log("time:",Date.now());
next();
});
// 定义网页的路由
router.get('/',function(req,res,next){
res.send('这是首页');
})
router.get('/about',function(req,res,next){
res.send('这是详情页');
})
module.exports = router;
然后再应用中加载路由模块
var birds = require('./birds');
...
app.use('/birds', birds);
应用即可处理localhost:9000/birds/和localhost:9000/birds/about的请求