简体   繁体   English

当使用Express Router时,这两行等效吗?

[英]When using Express Router are these two lines equivalent?

I could not find the official docs in a google search . 我在Google搜索中找不到官方文档。 Where are the official API docs for express.Router() and are lines 1 and 2 the same? express.Router()的官方API文档在哪里,第1行和第2行是否相同?

If so, is it just a matter of preference on which to use? 如果是这样,这仅仅是使用偏好的问题吗?

const express = require('express');
const router = express.Router();

router.get('path', callback); // line 1
router.route('path').get(callback); // line 2

There are 3 ways with which you can declare routes in your application 您可以通过3种方式在应用程序中声明路由

These are: 这些是:

  1. app.get("path", fn)
  2. router.get("path", fn)
  3. router.route("path").get(fn)

All of the above functions are used to generate http request routes in your application. 以上所有功能均用于在您的应用程序中生成http请求路由。

The app.get is the most basic one and is not recommended for larger projects. app.get是最基本的一个,不建议用于大型项目。 The reason being it gives less flexibility in handling routes as compared to the express.router . 原因是与express.router相比,它在处理路由时灵活性较低。 In express applications you will be dealing with middlewares a lot. 在快速应用程序中,您将大量处理中间件。 Middlewares are functions that are executed before the controller function of your application 中间件是在应用程序的控制器功能之前执行的功能

For example, take a look at this line 例如,看看这条线

app.get("/user", verifyUser, createUser) ;` app.get("/user", verifyUser, createUser) ;`

Above, verifyUser is a middleware function that is called with (Request, Response, Next) arguments by the express framework, you can write your incoming request verification logic in verifyUser and can then call NextFunction to pass the control to the next function with is the createUser controller ; 上面的verifyUser是一个中间件函数, (Request, Response, Next) arguments by the express framework, you can write your incoming request verification logic in verifyUser and can then call使用(Request, Response, Next) arguments by the express framework, you can write your incoming request verification logic in verifyUser and can then call NextFunction to pass the control to the next function with is the createUser controller ;

You can have as many middlewares as you want in your route declaration. 您可以在路由声明中拥有任意数量的中间件。

What if you need to call verifyUser each time a user is created, removed, fetched or modified. 如果您每次创建,删除,获取或修改用户时都需要调用verifyUser For each of the actions, you need to define your routes like this: 对于每个动作,您都需要像这样定义路线:

  app.get("/user", verifyUser, fetchUser);
  app.put("/user", verifyUser, updateUser);
  app.post("/user", verifyUser, createUser);
  app.delete("/user", verifyUser, deleteUser);

In larger applications you need to defined different logics to different entities and routes. 在较大的应用程序中,您需要为不同的实体和路由定义不同的逻辑。

express.router solves the above problem by providing us a flexibility to define what to do when user lands the /user route before passing the request to the middleware. express.router通过为我们提供了一种灵活性,从而在将请求传递给中间件之前定义用户登陆/user路由时的操作,从而解决了上述问题。

The above code in express router can be written as follows: 快速路由器中的以上代码可以编写如下:

  // file: userRoutes.js
  const router = express.Router();

  router.use((req, res, next) => {
     verifyUser(req, res, next);
  });

  function verifyUser(req, res, next) {
    // verification logic here
    if (/** verification is successful */)
      return next(); // return to the controller
    res.status(400).json({ msg: "user does not exists" });
  }

  router.get("/user", fetchUser);
  router.put("/user", updateUser);
  router.post("/user", createUser);
  router.delete("/user", deleteUser);

  module.exports = router;

  // app.js
  const userRoutes = require("./userRoutes");
  app.use(userRoutes);

Things gets really simplified if we chain the http request methods in the following way: 如果我们以以下方式链接http请求方法,那么事情将会真正简化:

  router.route("/user")
        .get(fetchUser);
        .put(updateUser);
        .post(createUser);
        .delete(deleteUser);

Note: Above code is for explanation purpose only, there may be syntax errors, the code is not expected to run as it is. 注意:上面的代码仅用于解释目的,可能存在语法错误,预计该代码不能按原样运行。 User might need to alter the code to make it work. 用户可能需要更改代码才能使其正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM