完整程式碼,請洽: https://github.com/Zrn-code/Node-js-tutorial/tree/node-08
# 什麼是 Middleware
app.js | app.use((req,res)=>{ |
| console.log('new request made:'); |
| console.log('host: ', req.hostname); |
| console.log('host: ', req.path); |
| console.log('host: ', req.method); |
| }); |
# 使用 next()
函式
app.js | app.use((req,res,next)=>{ |
| console.log('new request made:'); |
| console.log('host: ', req.hostname); |
| console.log('host: ', req.path); |
| console.log('host: ', req.method); |
| next(); |
| }); |
| app.use((req,res,next)=>{ |
| console.log('in the next middleware.'); |
| next(); |
| }); |
# 第三方的 middleware
app.js | const morgan = require('morgan'); |
| app.use(morgan('dev')); |
# 動態資料
| app.use(express.static('public')); |
head.ejs | <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width-device-width, intital-scale-1.0"> |
| <title>Blogs |<%= title %></title> |
| <link rel="stylesheet" href="/style.css"> |
| </head> |