Intereting Posts

作为模块需要另一个文件夹内的文件夹为模块

server.js我有以下几点:

app.use( require( './server/rest-api/v1/products' ) ); app.use( require( './server/rest-api/v1/product-categories' ) ); app.use( require( './server/rest-api/v1/measuring-units' ) ); app.use( require( './server/rest-api/v1/inventory' ) ); app.use( require( './server/rest-api/v1/suppliers' ) ); ... 

我想要的是使/server/rest-api/v1模块,这意味着它需要一个index.js ,但它包含什么,所以我只需要在server.js执行以下操作:

 app.use( require( './server/rest-api/v1'); 

如果需要了解我所要求的内容,下面是作为模块的其中一个文件夹:

/server/rest-api/v1/products/index.js

 module.exports = (function () { var express = require( 'express' ), router = express.Router(), create_product = require( './create-product.controller.js' ), list_product = require( './list-product.controller.js' ), detail_product = require( './detail-product.controller.js' ), update_product = require( './update-product.controller.js' ); router.route( '/api/v1/purchases/products/new' ) .post( create_product.post ); router.route( '/api/v1/purchases/products/list' ) .get( list_product.get ); router.route( '/api/v1/purchases/products/detail/:id' ) .get( detail_product.get ); router.route( '/api/v1/purchases/products/update' ) .put( update_product.put ); return router; })(); 

Solutions Collecting From Web of "作为模块需要另一个文件夹内的文件夹为模块"

您希望/server/rest-api/v1/index.js公开一个使用子路由器的独特路由器,每个路由器对应您的文件夹之一( 产品产品类别等)

/server/rest-api/v1/index.js

 var express = require('express'), router = express.Router(), product_router = require('./products'), product_categories_router = require('./product_categories'); router.use(product_router); router.use(product_categories_router); // etc. module.exports = router; 

请注意 ,如果以这种方式处理多条路由,在安装路由器时,定义一次API入口点( '/api/v1' )可能会更方便。 这样你的“商业”路由器就不需要知道进入path(对他们来说应该没有关系),如果你有一天需要改变path的话,这很方便。

那么这又取决于你,你如何devise你的服务器:)

例如:

server.js

 app.use('/api/v1', require('./server/rest-api/v1')); 

/server/rest-api/v1/index.js

 var express = require('express'), router = express.Router(), product_router = require('./products'); router.use('/purchases/products', product_router); module.exports = router; 

/server/rest-api/v1/products/index.js

 var express = require('express'), router = express.Router(), create_product = require('./create-product.controller'); router.route('/new').post(create_product.post); module.exports = router;