nodejs(十九)Express中介軟體
阿新 • • 發佈:2018-11-06
var express = require('express')
var app = express()
//express中介軟體
//1.攔截所有 next表示繼續執行下面
app.use(function(req, res, next) {
console.log('攔截到了1')
next()
})
//2. 攔截以/xxx開頭的
app.use('/abc', function(req, res, next) {
console.log('攔截到了2')
next()
})
//3. 嚴格的攔截
app.get('/abc/a', function(req, res, next) {
console.log('攔截到了3')
next()
})
app.post('/abc/a', function(req, res, next) {
console.log('攔截到了3')
next()
})
app.get('/', function(req, res, next) {
fs.readFile('.d/sa./d.sa/.dsa', function(err, data) {
if (err) {
// 當呼叫 next 的時候,如果傳遞了引數,
// 則直接往後找到帶有四個引數的應用程式級別中介軟體
//可以用來攔截全域性異常
next(err)
}
})
})
// 配置錯誤處理中介軟體 因為攔截是有順序的,所以放到最後
app.use(function(err, req, res, next) {
res.status(500).send(err.message)
})
//如果沒有匹配的中介軟體,Express會輸出Cannot GET xxxx路徑
app.listen(4000, function() {
console.log('Server is running')
})