
路由
|
155
const staff = {
mitch: { name: "Mitch",
bio: 'Mitch is the man to have at your back in a bar fight.' },
madeline: { name: "Madeline", bio: 'Madeline is our Oregon expert.' },
walt: { name: "Walt", bio: 'Walt is our Oregon Coast expert.' },
}
app.get('/staff/:name', (req, res, next) => {
const info = staff[req.params.name]
if(!info) return next() // 最终会“走”到404处理函数
res.render('05-staffer', info)
})
注意看我们是怎样在路由中使用
:name
的。它会匹配任何字符串(不包括斜杠),然后把匹
配到的字符串放入
req.params
对象中,键就是
name
。这个特性以后会经常使用,尤其是在
创建
REST
API
的时候。你可以在路由中使用多个参数。例如,如果希望将职员按城市划
分,可以像下面这样做:
const staff = {
portland: {
mitch: { name: "Mitch", bio: 'Mitch is the man to have at your ...