NodeJS之express的路由淺析


路由路徑和請求方法一起定義了請求的端點,它可以是字符串、字符串模式或者正則表達式。后端在獲取路由后,可通過一系列類似中間件的函數去執行事務。

可使用字符串的路由路徑:

// 匹配根路徑的請求
app.get('/', function (req, res) {
  res.send('root');
});

// 匹配 /about 路徑的請求
app.get('/about', function (req, res) {
  res.send('about');
});

// 匹配 /random.text 路徑的請求
app.get('/random.text', function (req, res) {
  res.send('random.text');
});

可使用字符串模式的路由路徑:

// 匹配 acd 和 abcd
app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});

// 匹配 /abe 和 /abcde
app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});

可使用正則表達式的路由路徑:

// 匹配 butterfly、dragonfly,不匹配 butterflyman、dragonfly man等
app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

可以為請求處理提供多個回調函數,其行為類似中間件。唯一的區別是這些回調函數有可能調用 next('route') 方法而略過其他路由回調函數。可以利用該機制為路由定義前提條件,如果在現有路徑上繼續執行沒有意義,則可將控制權交給剩下的路徑。

路由句柄有多種形式,可以是一個函數、一個函數數組,或者是兩者混合,如下所示

使用一個回調函數處理路由:

app.get('/example', function (req, res) {
  res.send('Hello from A!');
});

使用多個回調函數處理路由(記得指定 next 對象):

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!');
});

使用回調函數數組處理路由:

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]);

混合使用函數和函數數組處理路由:

var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from D!');
});

 

可使用 express.Router 類創建模塊化、可掛載的路由句柄。Router 實例是一個完整的中間件和路由系統。

var log=require("./log/log");
var express=require("express");
var app=express();

//首先定義一個路由
var router=express.Router();

//使用中間件
router.use(function firstFunc(req,res,next){
    console.log("Time: ",Date.now());
    next();
});

//如果是根目錄
router.get("/",function(req,res){
    res.send("home page");
});

//如果是根目錄下的about目錄
router.get("/about",function(req,res){
    res.send("about page");
});

//使用路由
//可輸入http://127.0.0.1:8000/myRoot得到home page
//可輸入http://127.0.0.1:8000/myRoot/about得到about page
//在得到返回的page之前,會先執行firstFunc函數
app.use("/myRoot",router);

//開啟站點
app.listen(8000,function(){
    log.info("站點開啟")
});

通過路由,可以在返回頁面之前,先通過中間件執行若干事物,而且這些中間件是當前路由共享的,這樣可以省去許多重復代碼,增加代碼可利用率的有效性。還可以將Router注冊為模塊導出,代碼更加有可讀性。

 

注明:以上學習內容來自:http://www.expressjs.com.cn/guide/routing.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM