var express = require('express')
var fs = require('fs')
var app = express()
// app.get('/abc', function (req, res, next) {
// console.log('abc')
// // req.foo = 'bar'
// req.body = {}
// next()
// })
// app.get('/abc', function (req, res, next) {
// console.log(req.body)
// console.log('abc 2')
// })
app.get('/', function (req, res, next) {
fs.readFile('.d/sa./d.sa/.dsa', function (err, data) {
if (err) {
// return res.status(500).send('Server Error')
// 當調用 next 的時候,如果傳遞了參數,則直接往後找到帶有 四個參數的應用程式級别中間件
// 當發生錯誤的時候,我們可以調用 next 傳遞錯誤對象
// 然後就會被全局錯誤進行中間件比對到并處理之
next(err)
}
})
})
app.get('/', function (req, res, next) {
console.log('/ 2')
})
app.get('/a', function (req, res, next) {
fs.readFile('./abc', function (err, data) {
if (err) {
// return res.status(500).send('Server Error')
next(err)
}
})
})
//一般用于處理404中間件,顯示404界面,因為前面所有的中間件沒有比對到,隻有到這裡才能比對到,所有顯示404
//這裡隻是業務邏輯錯誤,比如說URL一大串錯誤的位址
//前面的比對不到正确的中間件,就從這裡比對到404頁面
app.use(function (req, res, next) {
res.send('404')
})
//這裡的是系統錯誤,比如說代碼中找不到對應的檔案和目錄之類的系統錯誤
// 配置錯誤進行中間件,帶有 四個參數的應用程式級别中間件
app.use(function (err, req, res, next) {
res.status(500).send(err.message)
})
app.listen(3000, function () {
console.log('app is running at port 3000.')
})