node.js - typescript express 中间件

标签 node.js express typescript

我有一个简单的 express 身份验证中间件。它检查标题,如果一切正常,它调用 next()

现在当我在“DoSomething”时,“this”等于全局而不是“Test”的实例并且 “this.DoSomeThingPrivate”未定义。

我试过了

DoSomeThingPrivate :() => void;

this.DoSomeThingPrivate = () => {
...
}

图案。但也不行。

import express = require('express');

var app = express();

class Test {    
    constructor() {        
    }

    DoSomething(req:express.Request, res:express.Response, next:Function) :void {       
        this.DoSomeThingPrivate();
    }

    private DoSomeThingPrivate() :void
    {       
    }
}

var test = new Test();

app.use(test.DoSomething);

Relates to this

任何想法...

谢谢

最佳答案

以下应该可以正常工作,即使用粗箭头表示 DoSomething 而不是 DoSomethingPrivate:

import * as express from 'express';

var app = express();

class Test {    
    constructor() {        
    }

    // important: 
    DoSomething = (req:express.Request, res:express.Response, next:express.NextFunction) => {       
        this.DoSomeThingPrivate();
    }

    private DoSomeThingPrivate() :void
    {       
    }
}

var test = new Test();

app.use(test.DoSomething);

注意:您不需要使用bind。还有 https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

关于node.js - typescript express 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27567119/

相关文章:

javascript - 即使我更新了 .bash_profile,所有 NPM 命令也不起作用

mysql - 将问号字符转义为 NodeJS 中 MySQL 查询的占位符

javascript - 文件名未用作 AWS S3 名称

angular - 如何根据角色启用组件/操作?

angular - 如何使用数组中的多个条件过滤对象?

node.js - 从两个管道流创建 Node.js 流

javascript - npm start 在 cmd 中不起作用,并且显示错误,如图所示?

javascript - Express 中的客户端服务器

node.js - 在 VS Code 中调试 Express 应用程序时“无法获取/”

TypeScript:具有自定义方法的工厂 - 第三步