简体   繁体   English

在带有express和connect的节点中使用中间件的最常见方法是什么

[英]What is the most common way to use a middleware in node with express and connect

Thinking about the correct way, how to make use of middlewares in a node.js web project using express and connect which is growing up at the moment. 考虑正确的方法,如何在目前正在发展的Express.connect中使用node.js Web项目中的中间件。

Of course there are middlewares right now wich has to pass or extend requests globally but in a lot of cases there are special jobs like prepare incoming data and in this case the middleware would only work for a set of http-methods and routes. 当然,现在有一些中间件必须在全球范围内传递或扩展请求,但是在很多情况下,会有一些特殊的工作,例如准备传入数据,在这种情况下,中间件只能用于一组http方法和路由。

I've a component based architecture and each component brings it's own middleware layer which can implement those for requests this component can handle. 我有一个基于组件的体系结构,每个组件都带来了自己的中间件层,该中间件层可以实现该组件可以处理的请求。 On app startup any required component is loaded and prepared. 在应用启动时,将加载并准备所有必需的组件。 Is it a good idea to bind the middleware code execution to URLs to keep cpu load lower or is it better to use middlewares only for global purposes? 将中间件代码执行绑定到URL以保持较低的CPU负载是一个好主意,还是仅将其用于全局目的更好?

Here's some dummy how an url related middleware look like. 这是一些与url相关的中间件外观的假人。

app.use(function(req, res, next) {            

        // Check if requested route is a part of the current component
        // or if the middleware should be passed on any request
        if (APP.controller.groups.Component.isExpectedRoute(req) ||
            APP.controller.groups.Component.getConfig().MIDDLEWARE_PASS_ALL === true) {
                // Execute the midleware code here
                console.log('This is a route which should be afected by middleware');
                ...
                next();                    
            }else{
                next();
            }
        });

It depends on your setup, but you can be creative. 这取决于您的设置,但是您可以发挥创造力。

Say that you want to run a certain middleware for GET requests with a /foo prefix. 假设您要为带有/foo前缀的GET请求运行某个中间件。 In that case, you can limit the number of calls to that middleware using something like this: 在这种情况下,您可以使用以下方法限制对该中间件的调用次数:

// matches '/foo', '/foo/bar', '/foo/bar/blah', ...
app.get('/foo*', YourMiddleware);

(replace app.get with app.all to pass all request methods through the middleware, etc.) (替换app.getapp.all通过中间件传递所有请求方法等)

If you want to run the middleware only a limited number (one or two) specific routes, you can inject it in the route declaration: 如果只想运行中间件有限的(一两个)特定路由,则可以将其插入路由声明中:

app.get('/bar', YourMiddleware, function(req, res) {
  ...
});

If you have specific sets of middlewares, you can create arrays of them which you can use similarly: 如果您有特定的中间件集,则可以创建它们的数组,以类似的方式使用它们:

var MiddlewareSet = [ MiddlewareA, MiddlewareB, MiddlewareC ];
...
app.get('/', MiddlewareSet, function(req, res) {
  ...
});

This is like probability. 这就像概率。 Let us assume, there is 10 urls and your middleware is going to be execute for 7 or 8 urls. 我们假设有10个URL,并且您的中间件将针对7个或8个URL执行。 Then the better idea is, use your middleware global or otherwise use them as normal function. 更好的主意是,全局使用中间件,否则将它们用作常规功能。

Of course, you can do it either way. 当然,您可以选择任何一种方式。 Hopefully there is no big performance variation, because there is some reasons you have to think about, 希望不会有太大的性能差异,因为您必须考虑一些原因,

  1. Unlike PHP, Node.Js application read all of your code store them it in memory when app start. 与PHP不同,Node.Js应用程序读取所有代码,并在应用程序启动时将其存储在内存中。 So there is no run-time inclusion of code. 因此,没有运行时包含代码。

  2. Any way you have to stop block execution by using some function(middleware function). 您必须使用某种功能(中间件功能)以任何方式停止块执行。 The function may do actual operation or check whether the url is eligible to execute actual operation or not(like the code in your post) 该函数可能会执行实际操作或检查该网址是否符合执行实际操作的条件(例如您帖子中的代码)

Note: Whatever it is, your code should be readable and meaningful and intended to complete operation 注意:无论是什么,您的代码都应该可读且有意义,并旨在完成操作

Note***: More important you can not avoid cpu load "Javascript/Node.JS". 注意***:更重要的是您不能避免cpu加载“ Javascript / Node.JS”。 However you can manage it by keep all your variable in local scope as much as possible. 但是,您可以通过将所有变量尽可能保留在本地范围内来进行管理。 So that, the inbuilt garbage collector do the same for you effectively. 因此,内置的垃圾收集器可以有效地为您执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM