【问题标题】:Difference between app.get and router.get (Express)app.get 和 router.get (Express) 之间的区别
【发布时间】:2020-01-27 00:14:47
【问题描述】:

我个人更喜欢第一种方法,因为我觉得它将我的逻辑保留在控制器中,并且当它们所做的只是使用控制器中的方法并将其映射到路由时,我的路由非常明显。

但我是一名非常初级的开发人员,我不断发现人们更多地使用第二种方法。如果我的方法不好以及为什么会有比我更多知识的人向我解释。我都了解,但正如我所说,我才刚刚开始我的开发人员职业生涯,我需要使我的代码可读/简单,所以我需要了解哪种方法更适合什么情况。

谢谢!

//this is /routes/product.ts

import product from "../controllers/Product";


module.exports = function(app: Application) {
  app.get("/api/product", product.getAll);
  app.post("/api/product", product.create);
  app.get("/api/product/:_id", product.getOne);
  app.put("/api/product/:_id/edit", product.update);
  app.delete("/api/product/:_id", product.delete);
};



---------------------------------------------------
//this is app.ts

import express, { Application } from "express";

class App {
  app: Application;

  constructor() {
    this.app = express();
    this.routes();
  }


  routes() {
    require("../routes/product")(this.app);
  }
 
  }
}
export default App;

//this is .routes/index.ts
import { Router, Request, Response } from "express";
import Product from "../models/Product";


const router = Router();

router
  .route("/create")
  .get((req: Request, res: Response) => {
    res.render("product/create");
  })
  .post(async (req: Request, res: Response) => {
    const { title, description } = req.body;
    const newProduct = new Product({ title, description });
    await newProduct.save();
    res.redirect("/product/list");
  });
  
  
export default router;



----------------------------------------------------

//this is app.ts

import express, { Application } from "express";

import indexRoute from "./routes/index";

class App {
  app: Application;

  constructor() {
    this.app = express();
    this.routes();
  }

  routes() {
    this.app.use(indexRoute);

  }
}
export default App;

【问题讨论】:

    标签: javascript node.js typescript express


    【解决方案1】:

    绝对没有区别,事实上app实际上是一个Router内部(或者至少它内部使用了一个)。

    使用路由器的主要优点是:

    • 路由器级中间件,您的方法意味着添加的任何中间件都将应用于所有路由。
    • 路由器级错误处理,您可以捕获错误并阻止它冒泡到全局错误处理程序(如有必要)。
    • 相对 URL,您的方法意味着您每次都需要指定完整的子路径,即 /api/products/:_id/edit Vs /:_id/edit
    • Router 插件非常适合 Express(它们的工作方式与任何其他中间件一样)
    • 必要时更容易进行单元测试

    【讨论】:

    • 在第二个示例中,路径如何以及在何处添加到Router
    • @SoumyaKanti OP 在示例中实际上并没有做到这一点,但是如果您想使用相对路径,那么在配置路由器时添加基本路径,例如app.use("/api/user", userRouter)
    猜你喜欢
    • 2017-06-09
    • 2019-06-27
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2015-04-03
    • 2013-11-29
    • 2018-11-03
    • 2016-04-14
    相关资源
    最近更新 更多