繁体   English   中英

无法访问方法内的类属性

[英]Cannot access class properties inside a method

我开始学习 node.js,目前我正在努力使用我在 node.js 中编写的中间件。 它应该是一个错误处理程序。 问题是我无法访问我在构造函数方法中定义的属性。 我收到此错误:

类型错误:无法读取未定义的 notFound(/[无关]/src/middleware/ErrorHandler.js:12:8) 的属性“响应”

这是我的代码:

错误处理程序

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()

路由.api.js

// Import modules
const express = require('express')
const router = express.Router()

// Import controller
const contactController = require('../controllers/ContactController')

// Import error handler
const errorHandler = require('../middleware/ErrorHandler')

router.post('/contact', contactController.index)

// return 404 if no matching routes were found
router.use(errorHandler.notFound)

module.exports = router

也许代码没有任何意义,我只需要知道导致错误的原因,这不是用于生产目的的代码。

提前谢谢你,祝你有美好的一天

像这样定义你的方法:notFound=(req, res, next) =>{}

您正在将函数errorHandler.notFound传递给中间件。 下次调用时,它不会绑定到您导出的对象。

所以this不会是你的new ErrorHandler() 如果您想实现这一点,您可以做两件事: 方法绑定到构造函数中的this

或者使用@Gogu 提到的箭头函数 箭头函数从定义它们的环境中获取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM