NodeJS / Express:什么是“ app.use”?

吕树
2023-12-01

本文翻译自:NodeJS / Express: what is “app.use”?

In the docs for the NodeJS express module , the example code has app.use(...) . app.use(...) express模块文档中 ,示例代码具有app.use(...)

What is the use function and where is it defined? use功能是什么,在哪里定义?


#1楼

参考:https://stackoom.com/question/Lvh1/NodeJS-Express-什么是-app-use


#2楼

use is a method to configure the middleware used by the routes of the Express HTTP server object. use是一种配置Express HTTP服务器对象的路由所使用的中间件的方法。 The method is defined as part of Connect that Express is based upon. 该方法定义为Express基于的Connect的一部分。

Update Starting with version 4.x, Express no longer depends on Connect . 更新从版本4.x开始,Express不再依赖Connect

The middleware functions that were previously included with Express are now in separate modules; Express以前包含的中间件功能现在位于单独的模块中; see the list of middleware functions . 请参阅中间件功能列表


#3楼

The app object is instantiated on creation of the Express server. app对象在创建Express服务器时实例化。 It has a middleware stack that can be customized in app.configure() (this is now deprecated in version 4.x) . 它具有可以在app.configure()自定义的中间件堆栈 (现在在4.x版本中已弃用)

To setup your middleware, you can invoke app.use(<specific_middleware_layer_here>) for every middleware layer that you want to add (it can be generic to all paths, or triggered only on specific path(s) your server handles), and it will add onto your Express middleware stack. 要设置中间件,您可以为要添加的每个中间件层调用app.use(<specific_middleware_layer_here>) (可以对所有路径通用,也可以仅在服务器处理的特定路径上触发)。将添加到您的Express中间件堆栈中。 Middleware layers can be added one by one in multiple invocations of use , or even all at once in series with one invocation. 中间件层可以在use多个调用中一个接一个地添加,甚至可以一次调用一次全部添加。 See use documentation for more details. 有关更多详细信息,请参见use文档

To give an example for conceptual understanding of Express Middleware, here is what my app middleware stack (app.stack) looks like when logging my app object to the console as JSON: 为了举例说明Express Middleware的概念,这是将我的应用程序对象作为JSON登录到控制台时我的应用程序中间件堆栈(app.stack)的外观:

stack: 
   [ { route: '', handle: [Function] },
     { route: '', handle: [Function: static] },
     { route: '', handle: [Function: bodyParser] },
     { route: '', handle: [Function: cookieParser] },
     { route: '', handle: [Function: session] },
     { route: '', handle: [Function: methodOverride] },
     { route: '', handle: [Function] },
     { route: '', handle: [Function] } ]

As you might be able to deduce, I called app.use(express.bodyParser()) , app.use(express.cookieParser()) , etc, which added these express middleware 'layers' to the middleware stack. 如您所能推断的那样,我调用了app.use(express.bodyParser())app.use(express.cookieParser())等,这将这些表达的中间件“层”添加到了中间件堆栈中。 Notice that the routes are blank, meaning that when I added those middleware layers I specified that they be triggered on any route. 注意,这些路由是空白的,这意味着当我添加这些中间件层时,我指定了它们会在任何路由上触发。 If I added a custom middleware layer that only triggered on the path /user/:id that would be reflected as a string in the route field of that middleware layer object in the stack printout above. 如果我添加了仅在/user/:id路径上触发的自定义中间件层,则该中间件层将在上面的堆栈打印输出中的该中间件层对象的route字段中反映为字符串。

Each layer is essentially adding a function that specifically handles something to your flow through the middleware. 每层本质上都添加了一个功能,该功能专门处理通过中间件的流程中的某些内容。

Eg by adding bodyParser , you're ensuring your server handles incoming requests through the express middleware . 例如通过添加bodyParser您确保服务器通过快速中间件处理传入的请求 So, now parsing the body of incoming requests is part of the procedure that your middleware takes when handling incoming requests -- all because you called app.use(bodyParser) . 因此, 现在解析传入请求的主体是中间件在处理传入请求时所采用的过程的一部分 -所有这些都是因为您调用了app.use(bodyParser)


#4楼

app.use() used to Mounts the middleware function or mount to a specified path,the middleware function is executed when the base path matches. app.use()用于挂载中间件功能或挂载到指定路径,当基本路径匹配时执行中间件功能。

For example: if you are using app.use() in indexRouter.js , like this: 例如:如果您在indexRouter.js中使用app.use(),如下所示:

//indexRouter.js

var adsRouter = require('./adsRouter.js');

module.exports = function(app) {
    app.use('/ads', adsRouter);
}

In the above code app.use() mount the path on '/ads' to adsRouter.js. 在上面的代码app.use()中,将路径“ / ads”安装到adsRouter.js。

Now in adsRouter.js 现在在adsRouter.js中

// adsRouter.js

var router = require('express').Router();
var controllerIndex = require('../controller/index');
router.post('/show', controllerIndex.ads.showAd);
module.exports = router;

in adsRouter.js, the path will be like this for ads- '/ads/show', and then it will work according to controllerIndex.ads.showAd(). 在adsRouter.js中,广告-/ ads / show的路径将是这样,然后它将根据controllerIndex.ads.showAd()起作用。

app.use([path],callback,[callback]) : we can add a callback on the same. app.use([path],callback,[callback]):我们可以在同一位置添加一个回调。

app.use('/test', function(req, res, next) {

  // write your callback code here.

    });

#5楼

app.use() works like that: app.use()的工作方式如下:

  1. Request event trigered on node http server instance. 在节点http服务器实例上触发的请求事件。
  2. express does some of its inner manipulation with req object. express对req对象进行一些内部操作。
  3. This is when express starts doing things you specified with app.use 这是Express开始执行您通过app.use指定的操作时的时间

which very simple. 这很简单。

And only then express will do the rest of the stuff like routing. 然后只有express才能完成路由之类的其余工作。


#6楼

Middleware is a general term for software that serves to "glue together" so app.use is a method to configure the middleware, for example: to parse and handle the body of request: app.use(bodyParser.urlencoded({ extended: true })); 中间件是用于“粘合在一起”的软件的通用术语,因此app.use是一种配置中间件的方法,例如:解析和处理请求主体:app.use(bodyParser.urlencoded({ })); app.use(bodyParser.json()); app.use(bodyParser.json()); there are many middlewares you can use in your express application just read the doc : http://expressjs.com/en/guide/using-middleware.html 只需阅读doc,您就可以在快速应用程序中使用许多中间件: http : //expressjs.com/en/guide/using-middleware.html

 类似资料: