node.js express.Router 和 app.get 的区别?

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

Differences between express.Router and app.get?

node.jsexpress

提问by nelson687

I'm starting with NodeJS and Express 4, and I'm a bit confused. I been reading the Express website, but can't see whento use a route handler or when to use express.Router.

我从 NodeJS 和 Express 4 开始,我有点困惑。我一直在阅读 Express 网站,但看不到何时使用路由处理程序或何时使用express.Router.

As I could see, if I want to show a page or something when the user hits /showfor example I should use:

如我所见,如果我想在用户点击时显示页面或其他内容,/show我应该使用:

var express = require('express')    
var app = express()    
app.get("/show", someFunction)  

At the beginning, I thought this was old (for Express 3). Is that right or this is the way for Express 4 too?

一开始,我认为这是旧的(对于 Express 3)。是这样吗,或者这也是 Express 4 的方式?

If this is the way to do it in Express 4, what is express.Routerused for?

如果这是 Express 4 中的做法,那是express.Router用来做什么的?

I read almost the same example as above but using express.Router:

我阅读了与上面几乎相同的示例,但使用了express.Router

var express = require('express');
var router = express.Router();
router.get("/show", someFunction)

So, what's the difference between both examples?

那么,这两个例子有什么区别呢?

Which one should I use if I just want to do a simple testing website?

如果我只想做一个简单的测试网站,我应该使用哪个?

回答by Nocturno

app.js

应用程序.js

var express = require('express'),
    dogs    = require('./routes/dogs'),
    cats    = require('./routes/cats'),
    birds   = require('./routes/birds');

var app = express();

app.use('/dogs',  dogs);
app.use('/cats',  cats);
app.use('/birds', birds);

app.listen(3000);

dogs.js

狗.js

var express = require('express');

var router = express.Router();

router.get('/', function(req, res) {
    res.send('GET handler for /dogs route.');
});

router.post('/', function(req, res) {
    res.send('POST handler for /dogs route.');
});

module.exports = router;

When var app = express()is called, an app object is returned. Think of this as the main app.

var app = express()被调用时,返回一个 app 对象。将此视为主要应用程序

When var router = express.Router()is called, a slightly different mini appis returned. The idea behind the mini appis that each route in your app can become quite complicated, and you'd benefit from moving all that code into a separate file. Each file's router becomes a mini app, which has a very similar structure to the main app.

var router = express.Router()被调用时,返回一个略有不同的小应用程序迷你应用程序背后的想法是,应用程序中的每条路径都可能变得非常复杂,将所有代码移动到一个单独的文件中会让您受益匪浅。每个文件的路由器都成为一个迷你应用程序,其结构与主应用程序非常相似。

In the example above, the code for the /dogsroute has been moved into its own file so it doesn't clutter up the main app. The code for /catsand /birdswould be structured similarly in their own files. By separating this code into three mini apps, you can work on the logic for each one in isolation, and not worry about how it will affect the other two.

在上面的示例中,/dogs路由的代码已移动到其自己的文件中,因此它不会使主应用程序混乱。/cats/birds的代码在它们自己的文件中的结构类似。通过将此代码分成三个小应用程序,您可以单独处理每个应用程序的逻辑,而不必担心它会如何影响其他两个应用程序。

If you have code (middleware) that pertains to all three routes, you can put it in the main app, before the app.use(...)calls. If you have code (middleware) that pertains to just one of those routes, you can put it in the file for that route only.

如果您有与所有三个路由相关的代码(中间件),您可以在调用之前将其放在主 app 中app.use(...)。如果您的代码(中间件)仅与这些路由之一有关,则可以将其放入该路由的文件中。

回答by Alireza Fattahi

Express 4.0 comes with the new Router. As mentioned on the site:

Express 4.0 带有新的路由器。正如网站上提到的:

The express.Router class can be used to create modular mountable route handlers. A Router instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.

express.Router 类可用于创建模块化可安装路由处理程序。Router 实例是一个完整的中间件和路由系统;因此,它通常被称为“迷你应用程序”。

There is a good article at https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4which describes the differences and what can be done with routers.

https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4 上有一篇很好的文章,它描述了路由器之间的差异以及可以做什么。

To summarize

总结一下

With routers you can modularize your code more easily. You can use routers as:

使用路由器,您可以更轻松地模块化代码。您可以将路由器用作:

  1. Basic Routes: Home, About
  2. Route Middleware to log requests to the console
  3. Route with Parameters
  4. Route Middleware for Parameters to validate specific parameters
  5. Validates a parameter passed to a certain route
  1. 基本路线:首页,关于
  2. 路由中间件将请求记录到控制台
  3. 带参数的路由
  4. 用于参数的路由中间件以验证特定参数
  5. 验证传递给某个路由的参数

Note:

笔记:

The app.routerobject, which was removed in Express 4, has made a comeback in Express 5. In the new version, it is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.

app.router对象在 Express 4 中被删除,在 Express 5 中又卷土重来。在新版本中,它只是对基本 Express 路由器的引用,不像在 Express 3 中,应用程序必须显式加载它。

回答by TILAK

app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Post a random book')
  })

As in above example, we can add different HTTP request method under a route.

如上例,我们可以在一个路由下添加不同的 HTTP 请求方法。

回答by raj240

Let's say your application is little complex. So what we do first is we divide the application into multiple modules so that changes in one module doesn't clutter the others and you can keep working on individual modules, but at the end of the day you need to integrate everything into one since you are building a single application. It is like we have one main application and few child applications whose parent is the main application. So when we create the parent application we create one using

假设您的应用程序有点复杂。因此,我们首先要做的是将应用程序划分为多个模块,这样一个模块中的更改就不会干扰其他模块,并且您可以继续处理各个模块,但是在一天结束时,您需要将所有内容集成到一个模块中,因为您正在构建单个应用程序。这就像我们有一个主应用程序和几个子应用程序,其父应用程序是主应用程序。因此,当我们创建父应用程序时,我们使用

var express = require('express');
var parent = express();

And to this parent application we need to bring in the child applications. But since the child applications are not totally different applications(since they run in the same context-java term), express provides the way to do it by means on the Expresse's Router function and this is what we do in the each child module file and lets call one such child module as aboutme.

对于这个父应用程序,我们需要引入子应用程序。但是由于子应用程序并不是完全不同的应用程序(因为它们运行在相同的上下文-java 术语中),express 提供了通过 Expresse 的路由器函数来实现的方法,这就是我们在每个子模块文件中所做的让我们将一个这样的子模块称为aboutme

var express = require('express');
var router = express.Router();
/**
** do something here
**/
module.exports = router;

By module.exportswe are making this module available for other to consume and since we have modularized things we need to make the module files available to the parent application by means of node's require function just like any other third party modules and the parent file looks something like this.

通过module.exports,我们让这个模块可供其他人使用,因为我们已经模块化了东西,我们需要像任何其他第三方模块一样通过节点的require函数使模块文件对父应用程序可用,并且父文件看起来像这样的东西。

var express = require('express') 
var parent = express() 
var child = require(./aboutme)

after we make this child module available to the parent we need to tell the parent application when to use this child application. Lets say when a user hits the path aboutme we need the child application about me to handle the request and we do it by using the Expresse's usemethod.

在我们将此子模块提供给父模块后,我们需要告诉父应用程序何时使用此子应用程序。假设当用户点击关于我的路径时,我们需要关于我的子应用程序来处理请求,我们使用 Expresse 的use方法来完成。

parent.use('/aboutme',  aboutme);

and in one shot the parent file looks like this

并且在一次拍摄中,父文件看起来像这样

var express = require('express');
var parent = express();
var child = require(./aboutme);
/***
**do some stuff here
**/
parent.use('/aboutme',child);

Above all what the parent can do is it can start a server where as the child cannot.Hope this clarifies. For more information you can always look at the source code which takes some time but it gives you a lot of information. Thank you.

最重要的是,父母可以做的是它可以启动一个服务器,而孩子却不能。希望这能澄清。有关更多信息,您可以随时查看源代码,这需要一些时间,但它为您提供了很多信息。谢谢你。

回答by Ahmed Alawady

express.Routerhas many options:

express.Router有很多选择:

  • enable case sensitivity: /showroute to not be the same as /Show, this behavior is disabled by default
  • strict routing mode: /show/route to not the same as /show, this behavior is also disabled by default
  • we can add specific middleware/s to specific routes
  • 启用区分大小写:/show路由与 不同/Show,默认情况下禁用此行为
  • 严格路由模式:/show/路由到不一样/show,这个行为默认也是禁用的
  • 我们可以将特定的中间件添加到特定的路由

回答by T.Soundarya

using app.js to write routes means that they are accessible to all the users as app.js is loaded on application start. However, putting routes in express.router() mini apps protect and restrict their accessibility.

使用 app.js 编写路由意味着所有用户都可以访问它们,因为 app.js 在应用程序启动时加载。但是,将路由放入 express.router() 迷你应用程序可以保护和限制其可访问性。

回答by yuanfang wang

In a word , express.Routercan do more things when compares to app.get(),such as middleware, moreover, you can define one more router object with express.Router()

总之,express.Router相比于可以做更多的事情app.get(),比如中间件,而且,你可以定义一个更多的路由器对象express.Router()