use是express調用中間件的方法,它返回一個函數。下面是一個連續調用兩個中間件的例子。
~~~
var express = require("express");
var http = require("http");
var app = express();
app.use(function(request, response, next) {
console.log("In comes a " + request.method + " to " + request.url);
next();
});
app.use(function(request, response) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello world!\n");
});
http.createServer(app).listen(1337);
~~~
上面代碼先調用第一個中間件,在控制臺輸出一行信息,然后通過next方法,調用第二個中間件,輸出HTTP回應。由于第二個中間件沒有調用next方法,所以不再request對象就不再向后傳遞了。
使用use方法,可以根據請求的網址,返回不同的網頁內容。
~~~
var express = require("express");
var http = require("http");
var app = express();
app.use(function(request, response, next) {
if (request.url == "/") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
} else {
next();
}
});
app.use(function(request, response, next) {
if (request.url == "/about") {
response.writeHead(200, { "Content-Type": "text/plain" });
} else {
next();
}
});
app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
});
http.createServer(app).listen(1337);
~~~
上面代碼通過request.url屬性,判斷請求的網址,從而返回不同的內容。
除了在回調函數內部,判斷請求的網址,Express也允許將請求的網址寫在use方法的第一個參數。
~~~
app.use('/', someMiddleware);
~~~
上面代碼表示,只對根目錄的請求,調用某個中間件。
因此,上面的代碼可以寫成下面的樣子。
~~~
var express = require("express");
var http = require("http");
var app = express();
app.use("/", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
});
app.use("/about", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the about page!\n");
});
app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
});
http.createServer(app).listen(1337);
~~~
- 1. 概述
- 1.1 搭建HTTPs服務器
- 2. 運行原理
- 2.1 底層:http模塊
- 2.2 對http模塊的再包裝
- 2.3 什么是中間件
- 2.4 use方法
- 3. Express的方法
- 3.1 all方法和HTTP動詞方法
- 3.2 set方法
- 3.3 response對象
- 3.4 requst對象
- 4. 項目開發實例
- 4.1 編寫啟動腳本
- 4.2 配置路由
- 4.3 靜態網頁模板
- 5. 動態網頁模板
- 5.1 安裝模板引擎
- 5.2 新建數據腳本
- 5.3 新建網頁模板
- 5.4 渲染模板
- 5.5 指定靜態文件目錄
- 6. ExpressJS 4.0的Router用法
- 6.1 基本用法
- 6.2 router.route方法
- 6.3 router中間件
- 6.4 對路徑參數的處理
- 7. 上傳文件
- 8. 參考鏈接