[英]Exclude default routes form index.js file in Express.js app
I have an Express app where structure goes like this 我有一个Express应用,其中的结构是这样的
server/
|---/model
|---/routes
|---/controllers
|---index.js
In my index.js
file I'm handling default route for item
在我的
index.js
文件,我处理的默认路由item
//index.js
const item = require('./routes/item');
const app = express();
// Endpoint for all operations related with /item
app.use('/item', item);
In routes directory I have a file item.js 在路线目录中,我有一个文件item.js
//item.js
const express = require('express');
const router = express.Router();
const {
deleteItemById,
itemCreate,
getItemById,
updateItem
} = require('../controllers/item');
// Add new product
router.post('/create', itemCreate);
// Get product by id
router.get('/:id', getItemById);
// Delete product by id
router.delete('/:id/delete', deleteItemById);
// Update product by id
router.patch('/:id/update', updateItem);
module.exports = router;
The question is, how can I exclude line app.use('/item', item);
问题是,如何排除
app.use('/item', item);
to handle this route completely in routes/item.js file? 完全在routes / item.js文件中处理此路由? To have something like this in item.js file:
在item.js文件中包含以下内容:
router.use('/item')
router.post('foo bar')
router.get('foo bar);
and in my index only require('./routes/item.js)
并且在我的索引中只
require('./routes/item.js)
I don't think you can do exactly what you want but you might be able to get close by exporting a function from item.js
: 我不认为您可以完全按照自己的意愿进行操作,但是您可以通过从
item.js
导出函数来item.js
:
// item.js
const express = require('express')
const router = express.Router()
...
module.exports = (app) => app.use('/item', router)
...and then passing app
to it in index.js
: ...然后在
index.js
中将app
传递给它:
// index.js
const express = require('express')
const app = express()
require('./routes/item')(app)
I hope this helps. 我希望这有帮助。
This is the approach I use for handling routes within modules: 这是我用于处理模块内路由的方法:
// Init Express
const express = require ( 'express' );
const app = express ();
// Create a router (I use this approach to create multiple routers)
const apiRouter = express.Router ({});
// Include the routes module
require ( './api/v1.0/routes/item' ) ( apiRouter );
// ./api/v1.0/routes/item
module.exports = router => {
const itemController = require ( '../controllers/test' );
// Define routes here
router.post ( '/items', [
itemController.doPost
] );
router.get ( '/item/:id', [
itemController.getItem
] );
};
I create a separate router object this way so that I can create multiple routers if needed.. (one for UI app, one for API etc). 我以这种方式创建了一个单独的路由器对象,以便可以根据需要创建多个路由器。(一个用于UI应用程序,一个用于API等)。
Hope this helps.. 希望这可以帮助..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.