express 中介軟體 的概念
中介軟體
如果我的的get、post回撥函式中,沒有next引數,那麼就匹配上第一個路由,就不會往下匹配了。
如果想往下匹配的話,那麼需要寫next()
1app.get("/",function(req,res,next){
2console.log("1");
3next();
4});
5
6app.get("/",function(req,res){
7console.log("2");
8});
下面兩個路由,感覺沒有關係:
1app.get("/:username/:id",function(req,res){
2console.log("1");
3res.send("使用者資訊" + req.params.username);
4});
5
6app.get("/admin/login",function(req,res){
7console.log("2");
8res.send("管理員登入");
9});
但是實際上衝突了,因為admin可以當做使用者名稱 login可以當做id。
解決方法1:交換位置。 也就是說,express中所有的路由(中介軟體)的順序至關重要。
匹配上第一個,就不會往下匹配了。 具體的往上寫,抽象的往下寫。
1app.get("/admin/login",function(req,res){
2console.log("2");
3res.send("管理員登入");
4});
5
6app.get("/:username/:id",function(req,res){
7console.log("1");
8res.send("使用者資訊" + req.params.username);
9});
解決方法2:
1app.get("/:username/:id",function(req,res,next){
2var username = req.params.username;
3//檢索資料庫,如果username不存在,那麼next()
4if(檢索資料庫){
5console.log("1");
6res.send("使用者資訊");
7}else{
8next();
9}
10});
11
12app.get("/admin/login",function(req,res){
13console.log("2");
14res.send("管理員登入");
15});
路由get、post這些東西,就是中介軟體,中介軟體講究順序,匹配上第一個之後,就不會往後匹配了。next函式才能夠繼續往後匹配。
app.use()也是一箇中間件。與get、post不同的是,他的網址不是精確匹配的。而是能夠有小資料夾拓展的。
比如網址:http://127.0.0.1 :3000/admin/aa/bb/cc/dd
1app.use("/admin",function(req,res){
2res.write(req.originalUrl + "n");///admin/aa/bb/cc/dd
3res.write(req.baseUrl + "n");///admin
4res.write(req.path + "n");///aa/bb/cc/dd
5res.end("你好");
6});
如果寫一個/
1//當你不寫路徑的時候,實際上就相當於"/",就是所有網址
2app.use(function(req,res,next){
3console.log(new Date());
4next();
5});
app.use()就給了我們增加一些特定功能的便利場所。
實際上app.use()的東西,基本上都從第三方能得到。
● 大多數情況下,渲染內容用res.render(),將會根據views中的模板檔案進行渲染。如果不想使用views資料夾,想自己設定資料夾名字,那麼app.set("views","aaaa");
● 如果想寫一個快速測試頁,當然可以使用res.send()。這個函式將根據內容,自動幫我們設定了Content-Type頭部和200狀態碼。send()只能用一次,和end一樣。和end不一樣在哪裡?能夠自動設定MIME型別。
● 如果想使用不同的狀態碼,可以:
res.status(404).send('Sorry, we cannot find that!');
● 如果想使用不同的Content-Type,可以:
res.set('Content-Type', 'text/html');