Express 菜鳥筆記
阿新 • • 發佈:2018-12-05
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 中文文件