typescript 打字稿表达中间件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27567119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:56:58  来源:igfitidea点击:

Typescript express middleware

node.jsexpresstypescript

提问by Pintac

I have a simple auth middleware for express. It checks header and if all cool it calls next()

我有一个简单的快速认证中间件。它检查标题,如果一切都酷,它会调用 next()

Now when i am in "DoSomething" "this" is equal to global and not the instance of "Test" and "this.DoSomeThingPrivate" is undefined.

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

I have tried the

我已经尝试过

DoSomeThingPrivate :() => void;

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

pattern. But also does not work.

图案。但也不起作用。

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

与此有关

Any Ideas...

有任何想法吗...

thanks

谢谢

回答by basarat

The following should work fine i.e. use fat arrow for DoSomethingnot DoSomethingPrivate:

以下应该可以正常工作,即对DoSomethingnot使用胖箭头DoSomethingPrivate

import express = require('express');

var app = express();

class Test {    
    constructor() {        
    }

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

    private DoSomeThingPrivate() :void
    {       
    }
}

var test = new Test();

app.use(test.DoSomething);

Note:You should not need to use bind. Also https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

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

回答by johngeorgewright

You've passed a reference just to the function itself. The function's instance will be global. You need to bind the function to the instance of test.

您只传递了对函数本身的引用。该函数的实例将是全局的。您需要将该函数绑定到 的实例test

app.use(test.DoSomething.bind(test));