【发布时间】: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