【发布时间】:2023-01-27 19:06:45
【问题描述】:
我正在努力实现我的 express 路由器(实际上这是我的主路由器的“子路由器”,这就是我必须扩展 express.Router 的原因)
我有以下代码(作为示例,我将其简化为只有一种方法):
import express from "express";
export default class MandatoryFieldsSettingsRouter extends express.Router {
constructor() {
super();
this.get('/', this.retrieveMandatoryFieldsSettings);
}
async retrieveMandatoryFieldsSettings(req, res) {
//some treatment here
}
}
所以在创建应用程序主路由器的文件中,我可以像这样定义我的子路径:
router.use('/mandatory-fields-settings', new MandatoryFieldsSettingsRouter());
我在应用程序启动时出现以下错误 Error: Route.get() requires a callback function but got a [object Undefined],因为 this.retrieveMandatoryFieldsSettings 在构造函数中未定义。
我使用这个不同的方法声明修复了它:
// 1st impl : this one is the "wrong" one causing my error
async retrieveMandatoryFieldsSettings(req, res) {
//some treatment here
}
// 2nd impl : this one is the "good" one making my application working
retrieveMandatoryFieldsSettings = async function (req, res) {
//some treatment here
}
出于某种原因,我的公司希望我使用第一个实现。有什么方法可以使用它并保持我在构造函数中声明路径的方式吗? (我认为通过查看其构造函数来查看当前类中声明的每个路径更具可读性)。
我的公司并不封闭,如果绝对没有理由“禁止”第二次实施,请告诉我,如果您知道请解释两者之间的区别(-> 为什么第一个未定义而第二个没有? )
谢谢 !
【问题讨论】:
标签: javascript node.js express