翻看去年自己記錄的印象筆記,准備把筆記上的一些內容也同時更新到博客上,方便自己查看。
app.use(path,callback)中的callback既可以是router對象又可以是函數
app.get(path,callback)中的callback只能是函數
這說明,給app.get(app.post、app.put同理)賦個路由對象是不行的,其實,可以將app.get()看作app.use的特定請求(get)的簡要寫法。即
var express = require('express');
var app = express();
app.get('/hello',function(req,res,next){
res.send('hello test2');
});
等同於:
var express = require('express');
var app = express();
var router = express.Router();
router.get('/', function(req, res, next) {
res.send('hello world!');
});
app.use('/hello',router);
什么時用
那么,什么時用app.use,什么時用app.get呢?
路由規則是
app.use(path,router)
定義的,
router
代表一個由
express.Router()
創建的對象,在路由對象中可定義多個路由規則。可是如果我們的路由只有一條規則時,可直接接一個回調作為簡寫,也可直接使用
app.get
或
app.post
方法。即
當一個路徑有多個匹配規則時,使用app.use,否則使用相應的app.method(get、post)
總結:
app.use用來使用中間件( middleware)
2.Router
A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.路由器對象是中間件和路由的孤立實例。 您可以將其視為“微型應用程序”,只能執行中間件和路由功能。 每個Express應用程序都有一個內置的應用程序路由器
A router behaves like middleware itself, so you can use it as an argument to app.use() or as the argument to another router’s use() method.路由器的行為就像中間件本身,因此您可以將其用作app.use()的參數或作為另一路由器的use()方法的參數。
The top-level express object has a Router() function that creates a new router object.
Create a new router as follows:
var router = express.Router([options]);