Express 菜鸟笔记
基于
Node.js
平台,快速、开放、极简的
Web
开发框架。
使用
Express
可以快速地搭建一个完整功能的网站。
Express
框架核心特性:
-
可以设置中间件来响应
HTTP
请求 -
定义了路由表用于执行不同的
HTTP
请求动作 -
可以通过向模板传递参数来动态渲染
HTML
页面
安装
mkdir myapp
cd myapp
npm init
npm install express -save // save to package.json
生成器
npm install express-generator -g
express myapp
cd myapp
npm install
set DEBUG=myapp
npm start
极简示例
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('hello world!');
});
app.listen(3000);
路由
路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 方法(GET、POST 等)组成的
路由的定义由如下结构组成:app.METHOD(PATH, HANDLER)
app.METHOD(path, [callback…], callback)
app.post('/', function (req, res) {
res.send('Got a POST request');
});
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user');
});
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...');
next(); // pass control to the next handler
});
多个回调函数处理路由
app.get('/example/b', function (req, res, next) {
console.log('response will be sent by the next function ...');
next();
}, function (req, res) {
res.send('Hello from B!');
});
回调函数组处理路由
app.get('/example/c', [cb0, cb1, cb2]);
使用 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');
});
调用 next(‘route’) 方法将控制权交给下一个路由
// 一个中间件栈,处理指向 /user/:id 的 GET 请求
app.get('/user/:id', function (req, res, next) {
// 如果 user id 为 0, 跳到下一个路由
if (req.params.id == 0) next('route');
// 否则将控制权交给栈中下一个中间件
else next(); //
}, function (req, res, next) {
// 渲染常规页面
res.render('regular');
});
// 处理 /user/:id, 渲染一个特殊页面
app.get('/user/:id', function (req, res, next) {
res.render('special');
});
静态资源的托管与访问
// 托管
app.use(express.static('public'));
// 访问
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
}
}
app.use(express.static('public', options));
模板引擎
views,放模板文件的目录,比如:
app.set('views', './views')
view engine,模板引擎,比如:
app.set('view engine', 'jade')
html
head
title!= title
body
h1!= message
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
学习链接
- 中文官网
- Express 4.x API 中文手册
- 关于 Express 的书籍和博客
- Express 应用实例
- 菜鸟教程
- Express 4.x API 中文文档
版权声明:本文为Iron_Ye原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。