[英]node.js + express , routers in separated files and middleware only before certain routes?
[英]typescript node.js express routes separated files best practices
在Node项目中使用Express和Typescript,这将是express.Router的“最佳实践”。
示例目录结构
|directory_name
---server.js
|--node_modules
|--routes
---index.ts
|--admin
---admin.ts
|--products
---products.ts
|--authentication
---authentication.ts
所以在index.ts里面它会封装和管理所有的子路由器
//admin.ts (nested inside of index.ts)
import * as express from "express";
export = (() => {
let router = express.Router();
router.get('/admin', (req, res) => {
res.json({success: true});
});
return router;
})();
//index.ts (master file for express.Router) import * as express from "express"; //import sub-routers import * as adminRouter from "./admin/admin"; import * as productRouter from "./products/products"; export = (() => { let router = express.Router(); // mount express paths, any addition middleware can be added as well. // ex. router.use('/pathway', middleware_function, sub-router); router.use('/products', productRouter); router.use('/admin', adminRouter); //return for revealing module pattern return router; })(); //<--- this is where I don't understand something....
最后我们将设置我们的server.js
//the usual node setup
//import * as *** http, body-parser, morgan, mongoose, express <-- psudocode
import * as masterRouter from './routes/index'
var app = express();
//set-up all app.use()
app.use('/api', masterRouter);
http.createServer(app).listen(8080, () => {
console.log('listening on port 8080')
};
我的主要问题是index.ts(masterRouter文件)和它是IIFe的嵌套路由
export =(function(){})();
应该是为路由器编写打字稿模块的正确/最佳方法吗?
或者使用另一种模式会更好,也许是利用模式的模式
export function fnName(){} - export class cName {} - export default。
IIFe的原因是当我将它们导入另一个文件时,我不需要初始化模块,每种类型的路由器只会有1个实例。
在NodeJS中, 每个文件都是一个模块 。 声明变量不会污染全局命名空间 。 因此,您不需要使用良好的旧IIFE
技巧来正确定位变量(并防止全局污染/碰撞)。
你会写:
import * as express from "express";
// import sub-routers
import * as adminRouter from "./admin/admin";
import * as productRouter from "./products/products";
let router = express.Router();
// mount express paths, any addition middleware can be added as well.
// ex. router.use('/pathway', middleware_function, sub-router);
router.use('/products', productRouter);
router.use('/admin', adminRouter);
// Export the router
export = router;
https://basarat.gitbooks.io/typescript/content/docs/project/modules.html
我的主要问题是index.ts(masterRouter文件)和它的嵌套路由是IIFe的
export = (function(){})();
应该是为路由器编写打字稿模块的正确/最佳方式
http://memesvault.com/wp-content/uploads/Hell-No-Meme-Gif-13.jpg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.