我开始学习 Node.js,目前正在努力解决我用 Node.js 编写的中间件。它应该是一个错误处理程序。问题是我无法访问我在构造函数方法中定义的属性。我收到此错误:
TypeError:无法读取未定义 notFound 的属性“响应”(/[无关]/src/middleware/ErrorHandler.js:12:8)
这是我的代码:
错误处理程序.js
class ErrorHandler {
constructor() {
this.response = {
success: false,
errorMessage: '',
status: 0
}
}
notFound(req, res, next) {
this.response.errorMessage = 'Not Found'
this.response.status = 404
res.status(404).send(this.response)
}
badRequest(req, res, next) {
this.response.errorMessage = 'Bad request'
this.response.status = 400
res.status(400).send(this.response)
}
}
module.exports = new ErrorHandler()
Run Code Online (Sandbox Code Playgroud)
路由.api.js
// Import modules
const express = require('express')
const router = express.Router()
// Import controller
const contactController = require('../controllers/ContactController')
// Import error handler
const …Run Code Online (Sandbox Code Playgroud)