node.js 在 Express 中,app.router 究竟是做什么的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13254549/
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
In Express, what does app.router do exactly?
提问by Zsombor Erd?dy-Nagy
When I create a sample Express application using the express binary, the bootstrap code has these lines:
当我使用 express 二进制文件创建示例 Express 应用程序时,引导程序代码包含以下几行:
...
var app = express();
...
app.use(app.router);
I didn't find much about app.router. I thought that this is the middleware that handles the routing (app.get(), app.post() etc.) rules, but these rules also get executed when I remove the app.use(app.router); line.
我没有找到太多关于 app.router 的信息。我认为这是处理路由(app.get()、app.post() 等)规则的中间件,但是当我删除 app.use(app.router); 时,这些规则也会被执行;线。
So what is the exact purpuse of this middleware?
那么这个中间件的确切用途是什么?
采纳答案by Hector Correa
This is from the Express 2.x guide http://expressjs.com/2x/guide.html
这是来自 Express 2.x 指南http://expressjs.com/2x/guide.html
"Note the use of app.router, which can (optionally) be used to mount the application routes, otherwise the first call to app.get(), app.post(), etc will mount the routes."
“请注意 app.router 的使用,它可以(可选)用于挂载应用程序路由,否则第一次调用 app.get()、app.post() 等将挂载路由。”
I suspect this applies to Express 3.x too.
我怀疑这也适用于 Express 3.x。
回答by Charles Holbrow
In Express 3.x, app.router is an enhanced version of the connect middleware router. As hector said, this is were Express handles the request handlers registered with app.get, app.post, etc.
在 Express 3.x 中, app.router 是connect 中间件 router的增强版本。赫克托说,这是为快速处理与注册请求处理程序app.get,app.post等等。
If you do not call app.use(app.router)explicitly then express will call it implicitly the first time you use app.get(...), app.post(...), etc. However, you may want to .useit explicitly, because then you choose the the order of all your middleware.
如果您不app.use(app.router)显式调用,那么 express 将在您第一次使用app.get(...),app.post(...)等时隐式调用它。但是,您可能希望.use显式调用它,因为这样您就可以选择所有中间件的顺序。
app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
// app.get, app.post, etc called before static folder
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
See how the router is retrieved in the Express 3 source here.
在此处查看如何在 Express 3 源中检索路由器。
Note that Express 4 doesn't need app.router.
回答by Nitin .
This method has been deprecated
此方法已被弃用
why we use router ..because of we need to connect our sub app to our main app.
为什么我们使用路由器......因为我们需要将我们的子应用程序连接到我们的主应用程序。

