中间件功能或我使用它的方式是否有问题
const express = require('express')
const app = express()
const test = require('./middleware/test')
app.use(express.json())
app.use(test)
app.get('/home', (req,res) => {
console.log('home')
res.send("home")
})
middlewater函数在MIDDLEWARE文件夹
const test = ( err, req, res, next) => {
console.log("error mddleware is working")
next()
}
在中间件功能下添加module.exports = errorHandler
中间件函数未运行,因为"错误";论点。如果有err参数,则中间件将不会运行,直到抛出错误并通过next()
传递。确保正确使用错误。始终将处理程序放在端口侦听器之前的最后一个:
const express = require("express")
const app = express()
const errorHandler = require("./middleware/errorHandler")
app.use(express.json())
app.get("/home", (req, res) => {
console.log("home")
throw new Error("error")
res.send("home")
})
app.use(errorHandler)
app.listen(3000, () => console.log("server running on port 3000"))