首页 > 解决方案 > 在 Express.js 应用程序中从 index.js 文件中排除默认路由

问题描述

我有一个 Express 应用程序,其结构如下

server/
  |---/model
  |---/routes
  |---/controllers
  |---index.js

在我的index.js文件中,我正在处理默认路由item

//index.js
const item = require('./routes/item');
const app = express();

// Endpoint for all operations related with /item
app.use('/item', item);

在路由目录中,我有一个文件 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;

问题是,如何app.use('/item', item);在 routes/item.js 文件中排除行以完全处理此路由?在 item.js 文件中有这样的东西:

router.use('/item')
router.post('foo bar')
router.get('foo bar); 

并且仅在我的索引中require('./routes/item.js)

标签: javascriptnode.jsexpress

解决方案


我认为您不能完全按照自己的意愿做,但是您可以通过从以下位置导出函数来接近item.js

// item.js
const express = require('express')
const router = express.Router()

...

module.exports = (app) => app.use('/item', router)

...然后传递app给它index.js

// index.js
const express = require('express')
const app = express()

require('./routes/item')(app)

我希望这有帮助。


推荐阅读