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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11321635/
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-09-02 15:58:21  来源:igfitidea点击:

NodeJS / Express: what is "app.use"?

node.jsexpress

提问by Alexander Bird

In the docs for the NodeJS expressmodule, the example code has app.use(...).

NodeJSexpress模块文档中,示例代码有app.use(...).

What is the usefunction and where is it defined?

什么是use函数,它在哪里定义?

回答by chinnychinchin

The app object is instantiated on creation of the Express server. It has a middlewarestackthat can be customized in app.configure()(this is now deprecated in version 4.x).

app 对象在创建 Express 服务器时实例化。它有一个可以自定义的中间件堆栈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 Expressmiddleware stack. Middleware layers can be added one by one in multiple invocations of use, or even all at once in series with one invocation. See usedocumentationfor more details.

要设置您的中间件,您可以app.use(<specific_middleware_layer_here>)为要添加的每个中间件层调用(它可以对所有路径通用,或者仅在您的服务器处理的特定路径上触发),并且它将添加到您的Express中间件堆栈中。中间件层可以在 的多次调用中一层一层地添加use,甚至可以与一次调用串联在一起。有关更多详细信息,请参阅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. 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/:idthat would be reflected as a string in the routefield of that middleware layer object in the stack printout above.

您可能会推断出,我调用了app.use(express.bodyParser())app.use(express.cookieParser())等,它将这些快速中间件“层”添加到中间件堆栈中。请注意,路由是空白的,这意味着当我添加这些中间件层时,我指定它们在任何路由上触发。如果我添加了一个仅在路径/user/:id上触发的自定义中间件层,该路径将route在上面的堆栈打印输出中反映为该中间件层对象字段中的字符串。

Each layer is essentially adding a function that specifically handles something to your flow through the middleware.

每一层本质上都是添加一个函数,专门处理通过中间件的流程。

E.g. by adding bodyParser, you're ensuring your server handles incoming requests through the express middleware. 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).

例如,通过添加bodyParser您可以确保您的服务器通过 express 中间件处理传入的请求。因此,现在解析传入请求的主体是您的中间件在处理传入请求时所采取的过程的一部分——这一切都是因为您调用了app.use(bodyParser).

回答by JohnnyHK

useis a method to configure the middleware used by the routes of the Express HTTP server object. The method is defined as part of Connectthat Express is based upon.

use是一种配置 Express HTTP 服务器对象的路由所使用的中间件的方法。该方法被定义为Express 所基于的Connect 的一部分。

UpdateStarting 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; see the list of middleware functions.

以前包含在 Express 中的中间件功能现在位于单独的模块中;请参阅中间件功能列表

回答by Tyrese

Each app.use(middleware)is called every time a request is sent to the server.

每次向服务器发送请求时都会调用每个app.use(middleware)

回答by Shubham Verma

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-'/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.

    });

回答by Omkar Mote

app.use()acts as a middleware in express apps. Unlike app.get()and app.post()or so, you actually can use app.use()without specifying the request URL. In such a case what it does is, it gets executed every time no matter what URL's been hit.

app.use()在 express 应用中充当中间件。与app.get()app.post() 等不同,您实际上可以在不指定请求 URL 的情况下使用app.use()。在这种情况下,它的作用是,无论点击什么 URL,每次都会执行。

回答by Anton Stafeyev

app.use() works like that:

app.use() 是这样工作的:

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

which very simple.

这很简单。

And only then express will do the rest of the stuff like routing.

只有这样 express 才会做其他的事情,比如路由。

回答by HymanOfAshes - Mohit Gawande

app.use(function middleware1(req, res, next){
   // middleware1 logic
}, function middleware1(req, res, next){
   // middleware2 logic
}, ... middlewareN);

app.useis a way to register middleware or chain of middlewares(or multiple middlewares) before executing any end route logic or intermediary route logic depending upon order of middleware registration sequence.

app.use是一种在执行任何端路由逻辑或中间路由逻辑之前注册中间件或中间件链(或多个中间件)的方法,具体取决于中间件注册顺序。

Middleware:forms chain of functions/middleware-functionswith 3 parameters req, res, and next. next is callback which refer to next middleware-function in chain and in case of last middleware-function of chain next points to first-middleware-function of next registered middlerare-chain.

中间件:形成具有3 个参数 req、res 和 next函数/中间件函数链。next 是回调,它引用链中的下一个中间件函数,如果链的最后一个中间件函数 next 指向下一个注册的中间件链的第一个中间件函数。

回答by chetan awate

app.useis woks as middlewarefor app request. syntax

app.use是作为应用请求的中间件。句法

app.use('pass request format',function which contain request response onject)

example

例子

app.use('/',funtion(req,res){
 console.log(all request pass through it);
// here u can check your authentication and other activities.
})

also you can use it in case of routing your request.

您也可以在路由请求的情况下使用它。

app.use('/', roting_object);

回答by Hongnan Yan

app.useis a function requires middleware. For example:

app.use是一个需要中间件的功能。例如:

 app.use('/user/:id', function (req, res, next) {
       console.log('Request Type:', req.method);
        next();
     });

This example shows the middleware function installed in the /user/:idpath. This function is executed for any type of HTTP request in the /user/:idpath.

本示例展示了安装在/user/:id路径中的中间件功能。该函数针对/user/:id路径中的任何类型的 HTTP 请求执行。

It is similar to the REST Web Server, just use different /xxto represent different actions.

它类似于 REST Web Server,只是使用不同/xx来表示不同的动作。

回答by saurabh kumar

In express if we import express from "express" and use app = express(); then app having all functionality of express

在 express 中,如果我们从“express”导入 express 并使用 app = express(); 然后应用程序具有快递的所有功能

if we use app.use()

如果我们使用 app.use()

with any module/middleware function to use in whole express project

在整个快递项目中使用任何模块/中间件功能