what is app.use in NodeJS/Express

本文详细解释了NodeJS的Express框架中app.use方法的功能和用途。通过使用app.use可以定制中间件堆栈,控制请求处理流程。文章还提供了具体的示例帮助理解中间件如何在Express中工作。
up vote  108  down vote  favorite
31

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

What is the use function and where is it defined?

share | improve this question
 
2 
possible duplicate: stackoverflow.com/questions/7337572/… –  Alexander Bird  Jul 4 '12 at 2:30

2 Answers

up vote 130  down vote accepted

The app object is instantiated on creation of the Express server. It has a middleware stack that can be customized in app.configure()(this is now deprecated in version 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. Middleware layers can be added one by one in multiple invocations of use, or even all at once in series with one invocation. See use documentation for more details.

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:

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/:id that would be reflected as a string in the route field of that middleware layer object in the stack printout above.

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

E.g. by adding bodyParseryou'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).

share | improve this answer
 
39 
thank you. would it be so difficult for the express folks to explain this in their API docs? –  ericsoco  Jun 25 '13 at 21:52
3 
So you're saying that when a request is received the data is passed through those parsers before hitting the actual service. So for example: Valid Request->Authentication->ProcessesRequest->ServResponse USE would control those steps in a specific order and not execute them parallel? –  CyberMen  Oct 10 '13 at 19:10
2 
When is the function that is sent to app.use called? After creating the express server or for every request? –  Timo Huovinen  Nov 21 '13 at 18:25
1 
You should update this answer because apparently app.configure was removed from express in the last release. –  nbro  Oct 21 '15 at 11:35
1 
Projects generated by express use app.use to load routes. I don't consider my routes middleware, so is this another acceptable use case? –  Jon  Dec 9 '15 at 9:08

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

share | improve this answer
 
2 
3 
And the online docs are here: senchalabs.org/connect/proto.html#app.use –  Alexander Bird  Jul 4 '12 at 2:47
 
Would it be efficient if a Node middleware instantiates objects? Would this mean that on every request, that middleware instantiates new objects? Do the old objects get discarded? For example app.use(function(){ var object = new SomeConstructor; next(); }) –  CMCDragonkai  Mar 6 '14 at 14:01
1 
Short and sweet. –  mishap  Dec 13 '15 at 1:41
1 
@CMCDragonkai It's fine to instantiate objects on every request. They'll get garbage collected so long as you're not storing references to the objects outside the scope of your request handler. –  jeff_mcmahan  Dec 16 '15 at 2:45
内容概要:本文系统阐述了智能物流路径规划的技术体系与实践应用,涵盖其发展背景、核心问题建模、关键算法、多目标与动态环境处理、系统架构及典型应用场景。文章以车辆路径问题(VRP)及其变体为核心数学模型,介绍了从Dijkstra、A*等单智能体算法到多车VRP的元启发式求解方法(如遗传算法、蚁群算法、大规模邻域搜索),并深入探讨了多目标优化(成本、时间、碳排放)与动态环境(实时订单、交通变化)下的自适应规划策略。结合城市配送、干线运输、场内物流等案例,展示了路径规划在提升效率、降低成本方面的实际价值,并分析了当前面临的复杂性、不确定性等挑战,展望了AI融合、数字孪生、车路协同等未来趋势。; 适合人群:具备一定物流、运筹学或计算机基础,从事智能交通、物流调度、算法研发等相关工作的技术人员与管理人员,工作年限1-5年为宜。; 使用场景及目标:①理解智能物流路径规划的整体技术架构与核心算法原理;②掌握VRP建模方法与多目标、动态环境下路径优化的实现策略;③为物流系统设计、算法选型与系统优化提供理论依据与实践参考; 阅读建议:建议结合文中案例与数学模型,重点理解算法选择与实际业务场景的匹配逻辑,关注动态规划与多目标优化的工程实现难点,可配合仿真工具或开源求解器进行实践验证。
### 其他方法或镜像源下载Node.js版本 除了官方提供的下载方式,用户可以通过以下方法或镜像源获取Node.js版本。这些方法适用于不同操作系统和需求场景。 #### 方法一:通过nvm(Node Version Manager)安装特定版本 `nvm` 是一个用于管理多个 Node.js 版本的工具,支持在不同版本之间切换。以下是使用 `nvm` 安装特定版本的方法[^1]: ```bash # 安装特定版本的 Node.js nvm install 20.12.0 # 列出已安装的 Node.js 版本 nvm ls # 切换到指定版本 nvm use 20.12.0 # 设置默认版本 nvm alias default 20.12.0 ``` #### 方法二:通过国内镜像源下载Node.js 国内用户由于网络原因可能无法快速访问官方源,因此可以使用国内镜像源下载Node.js。以下是具体步骤[^2]: 1. 访问国内镜像站点,例如华为云镜像站:[https://mirrors.huaweicloud.com/nodejs/](https://mirrors.huaweicloud.com/nodejs/) 2. 下载所需版本的压缩包,例如: ```bash wget https://mirrors.huaweicloud.com/nodejs/v16.20.2/node-v16.20.2-linux-x64.tar.gz ``` 3. 解压并重命名文件夹: ```bash tar xf node-v16.20.2-linux-x64.tar.gz mv node-v16.20.2-linux-x64 node-v16.20.2 ``` #### 方法三:通过npm配置国内镜像源 如果需要下载Node.js相关依赖,可以通过设置npm的国内镜像源来加速下载过程[^3]: ```bash # 设置淘宝镜像源 npm config set registry https://registry.npmmirror.com # 查看当前使用的镜像源 npm config get registry ``` #### 方法四:Windows系统下的手动安装 对于Windows用户,可以直接从Node.js官网或其他可信镜像源下载安装包,并进行手动安装[^4]: 1. 访问Node.js官网:[https://nodejs.org/](https://nodejs.org/) 或国内镜像站。 2. 下载对应系统的安装包(如 `node-v20.18.0-x64.msi`)。 3. 运行安装包,按照提示完成安装。 4. 验证安装是否成功: ```bash node -v npm -v ``` #### 方法五:通过脚本自动化安装 对于Linux或macOS用户,可以使用脚本自动化安装Node.js。例如,使用 `curl` 和 `bash` 安装: ```bash curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash source ~/.bashrc nvm install --lts ``` ### 示例代码 以下是一个通过脚本安装Node.js的示例: ```bash # 自动化安装nvm和Node.js curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash source ~/.bashrc nvm install 20.12.0 nvm use 20.12.0 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值