【问题标题】:NodeJS export class cannot read property of undefinedNodeJS 导出类无法读取未定义的属性
【发布时间】:2020-08-30 17:16:58
【问题描述】:

我目前正在尝试向我的 NodeJS 项目添加一个服务层,这是我使用 express 和 sequelize 构建的一个简单 API。该项目具有通常的模型、路由和控制器(MRC)形式的结构;每个都有自己的目录。现在我需要做的就是添加另一个包含服务文件的目录。这些文件将以类的形式包含业务逻辑,我将导出并包含在我的控制器文件中。

这里我将展示控制器和服务文件:

eruptionController.js

const EruptionService = require('../services/eruptionService.js');
let Eruption = new EruptionService()


module.exports = {
    getEruptions: (req, res) => {
        Eruption.get().then(result => {
            return res.status(200).json({
                message: "Get All Eruptions",
                result
            })
        }).catch(err => {
            return res.status(200).json({
                message: "internal Server Error",
                error: err.message
            })
        })
    }
};

eruptionService.js

const { eruption } = require('../models');

class EruptionService {
    constructor () {
        this.eruptionModel = eruption;
        
    }

    get () {
        this.eruptionModel.findAll()
        .then(result => result)
        .catch(err => err)
    }
}

module.exports = EruptionService;

正如我们在此处看到的,在服务文件中,我从模型文件夹中导入了eruption 模型并将其包含在构造函数中。然后我创建了一个名为get的方法,用于从数据库中检索所有的喷发数据。

之后,我将EruptionService 类导入到控制器文件中,将其作为实例初始化,并将该类包含在getEruptions 函数中。然后该函数将以端点的形式在快速路由中使用。

问题是当我尝试向端点发送请求时,出现以下错误

TypeError: Cannot read property 'then' of undefined

根据错误,似乎 EruptionService 类没有正确导出,因为当我调用 mothed get 时,它是未定义的。

我已经被这个问题困扰了一段时间,我不确定发生了什么。基于this post,我似乎可以正确导出类。

我也尝试过以如下方式导出

module.exports = {EruptionService: EruptionService}

我也尝试过像这样导入

const EruptionService = require('../services/eruptionService.js');

但最终,它要么导致相同的错误,要么导致不同的一种错误。我想知道是否有人能指出我错过了什么?提前致谢

【问题讨论】:

  • 您的get() 方法没有return 承诺。导出没有问题 - 如果有,你会得到类似“EruptionService is not a constructor”的信息。
  • 顺便说一句,drop the pointless .then(result => result) 并在您无法实际处理错误时避免使用catch(例如,通过返回一个空列表作为后备)。
  • @Bergi 好的,请注意。谢谢!

标签: javascript node.js


【解决方案1】:

你应该返回一个 promise 函数来获取 then 函数。你的服务有问题,应该像下面的sn-p

 class EruptionService {
    constructor () {
        this.eruptionModel = eruption;
        
    }

    get () {
        return this.eruptionModel.findAll()
    }
}

【讨论】:

  • 现在get函数返回一个promise函数,它可以像promise一样使用,也可以用作async/await函数。
猜你喜欢
  • 2017-03-06
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 2022-11-29
  • 2023-02-17
  • 2017-06-17
相关资源
最近更新 更多