gabrielhelloworld
gabrielhelloworld

Reputation: 23

Difference between app.get and router.get (Express)

I personally prefer the first approach as I feel it keeps my logic inside the controller and my routes are super obvious when all they do is use a method from a controller and map it to a route.

But I am a very junior developer and I keep finding that people use the second approach more. Would anyone with more knowledge than I can explain to me if my approach is bad and why. I understand both, but as I said I am barely beginning my developer career and I need to make my code readable/simple so I need to learn what approach is better for what case.

Thanks!

//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;

Upvotes: 2

Views: 76

Answers (1)

James
James

Reputation: 82136

There is absolutely no difference, in fact, app is actually is a Router internally (or at least it uses one internally).

The main advantages of using a Router would be:

  • Router level middleware, your approach would mean any middleware added would be applied for all routes.
  • Router level error handling, you can catch an error and stop it from bubbling up to the global error handler (if necessary).
  • Relative URLs, your approach means you need to specify the full sub-path each time i.e. /api/products/:_id/edit Vs /:_id/edit
  • Routers plugin really nicely to Express (they work just like any other middleware)
  • Easier to unit test if necessary

Upvotes: 1

Related Questions