javascript - 在 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)
解决方案
我认为您不能完全按照自己的意愿做,但是您可以通过从以下位置导出函数来接近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)
我希望这有帮助。
推荐阅读
- xcode - 使用标记选择时禁用弹出消息?
- python - Python:2.7:NameError:未定义名称“数据”
- google-apps-script - Apps 脚本 - 创建谷歌表单但在同一个数据库中得到响应(电子表格)
- azure - 如何通过 API 在 Azure Devops 中添加团队成员?Groups API 也不起作用
- firebase - 远程配置未从控制台更新
- html - 如何与验证一起动态循环表单控件名称
- bash - 用于在 zip 文件中查找最新文件匹配模式的 Bash 函数
- javascript - 获取 this.startBreak() 不是 react.js 中的函数错误
- android - 挂钩运行后下载的 dex 文件
- python - i need to make a confusion matrix for a CNN model