【问题标题】:Couldn't call method inside method controller in route Nodejs Express Typescript无法在路由 Nodejs Express Typescript 中调用方法控制器内的方法
【发布时间】:2020-12-16 05:33:05
【问题描述】:

我有两节课; authenticationRoutes.ts 和 authenticationController.ts。在 authenticationRoutes 我调用“authenticationController.test”,“authenticationController.test”方法调用“authenticationController.generateAccessAuthToken”方法。每当我这样做时,我都会收到以下错误:未处理的拒绝类型错误:无法读取属性'generateAccessAuthToken' 未定义的

authenticationRoutes.ts
import { authenticationController } from '../controllers/authenticationController';

        //TEST ROUTE
        this.router.get('/users',  authenticationController.test);

authenticationController.ts


public test(req: Request, res: Response) {
        dbSequelize().User.findAll({
            where: {
                id: '0'
            },
            attributes: ['id']
        }).then((user: UserInstance[]) => {
            this.generateAccessAuthToken('0').then((response: any) => {
                console.log(response);
                res.send(response);
            });
        })
    }


generateAccessAuthToken(_id: any) {
        return new Promise(async (resolve, reject) => {
            await jwt.sign({ id: _id }, SECRET_KEY as string, function (err: Error, token: any) {
                if (err) {
                    reject(err);
                } else {
                    resolve(token);
                }
            })
        })
    }

我希望能够执行我所描述的操作而不会收到错误。

【问题讨论】:

    标签: node.js typescript express routes nodejs-server


    【解决方案1】:

    我认为这样可以解决问题:

    this.router.get('/users', authenticationController.test.bind(AuthenticationController));

    基本上,当您有一个带有方法b 的类A 时,如果您传递A.b 之类的:

    const a = new A();
    const b = a.b;
    b(); // now 'this' is lost, any reference to `this` in b() code would be undefined
    

    您正在传递仅函数。它现在与A 类无关,它只是一个函数

    因此,除其他外,您可以使用bind 为函数显式设置this 上下文:

    const a = new A();
    const b = a.b.bind(a);
    b(); // so now b() is forced to use a as this context
    

    我敢打赌,关于你的问题有很多重复,但我找不到任何人,因为搜索很棘手(this js 中的绑定有很多问题)。

    希望这会有所帮助。

    【讨论】:

    • 当我实例化控制器类时,它说该类不是构造函数
    【解决方案2】:

    我遇到了同样的问题并解决了:

    public test = (req: Request, res: Response) => {
            dbSequelize().User.findAll({
                where: {
                    id: '0'
                },
                attributes: ['id']
            }).then((user: UserInstance[]) => {
                this.generateAccessAuthToken('0').then((response: any) => {
                    console.log(response);
                    res.send(response);
                });
            })
        }
    

    【讨论】:

      猜你喜欢
      • 2016-07-03
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2015-06-02
      相关资源
      最近更新 更多