const express = require('express');
let app = express();app.get('/', function (req, res) {res.send('home page');
});app.listen(3000, 'localhost', 100, function (err) {if (err) {console.log('error');} else {console.log('the http server is running at localhost:3333');}
});
如果 name 是一個數組, 則回調觸發器按聲明的順序注冊在其中聲明的每個參數.此外, 對于每個已聲明的參數, 除了最后一個外, 回調中的下一個調用將調用下一個聲明的參數的回調.對于最后一個參數, 調用 next 將調用當前正在處理的路由的下一個中間件, 就像如果名稱只是一個字符串一樣.
參數是一個字符串
app.param('id', (req, res, next, id) => {console.log('called only once');next();
});app.get('/user/:id', (req, res, next) => {console.log('although this matches');next();
});app.get('/user/:id', (req, res) => {console.log('this matches too');res.send('end user id');
});
/**
called only once
although this matches
this matches too
*/
參數是一個數組
app.param(['id', 'page'], (req, res, next, id) => {console.log('called only once', id);next();
});app.get('/user/:id/:page', (req, res, next) => {console.log('although this matches');next();
});app.get('/user/:id/:page', (req, res) => {console.log('this matches too');res.send('end user id');
});
/**
called only once kkk
called only once 555
although this matches
this matches too
*/
1.13. app.path()
返回應用程序的規范化路徑
let express = require('express');
let app = express();
let blog = express();
let blogAdmin = express();app.use('/blog', blog);
blog.use('/admin', blogAdmin);console.log(app.path());
console.log(blog.path());
console.log(blogAdmin.path());
// this middleware will not allow the request to go beyond it
app.use((req, res, next) => {res.send('Hello World');
})// requests will never reach this route
app.get('/', (req, res) => {res.send('Welcome');
})