[英]How to combine route path if file in sub directory express
这是我的文件夹结构
项目
路线
授权
现在我的 server.js 看起来像这样
const express = require("express");
const app = express();
const registerRoutes = require("./routes/auth/register");
const registerAdminRoutes = require("./routes/auth/registerAdmin");
const loginRoutes = require("./routes/auth/login");
app.use("/api-frontend", registerRoutes);
app.use("/api-backOffice", verify.isAdmin, registerAdminRoutes);
app.use("/api-backOffice/auth", loginRoutes);
如您所见,如果我将来有很多路线,我认为这是很脏的代码。 我想要求所有路径进入 index.js 然后我想在我的server.js
中使用类似的东西
app.use('/api', required(./routes))
这是我尝试做的
在 routes/index.js 我需要所有路由
require("./auth/register");
require("./auth/login");
我不确定。 他们是否需要 1 次并获取文件夹中的所有文件以使其更干净。 在尝试做这样的事情之后,错误一直在server.js
中说
Router.use() requires a middleware function but got a Object
这是我的示例 register.js
const express = require("express");
const registerController = require("../../controllers/register");
const router = express.Router();
router.post(
"/register-with-social",
registerController.validate("createUser"),
registerController.registerWithSocial
);
module.exports = router;
如何将我的路由文件夹合并到 server.js 文件中的 1 行
你可以这样做:
router
object 将来自server.js
文件,您可以在此处使用,并在此处列出此模块的所有路由。
const registerController = require("../../controllers/register");
module.exports = (router) => {
router.post(
"/api-frontend/register-with-social",
registerController.validate("createUser"),
registerController.registerWithSocial
);
// you can add more routes below if you want
}
在此处加载所有模块的路由文件并将其导出。
module.exports = [
// AUTH REGISTER : ROUTES URL
require('./auth/register'),
// AUTH LOGIN : ROUTES URL
require('./auth/login'),
// List all your routes of auth module
];
服务器.js
您可以从
index.js
文件中初始化所有路由,加载并使用它。
const express = require("express");
const app = express();
const router = express.Router();
// just created a function,
// if you want to use direct code then you can
// if you want to store this function in any helper library then you can
async function bootstrap(uri, modules){
const index = require(uri);
for (let init of index) { await init(modules); }
}
bootstrap("./routes/index", router);
app.use('/api', router);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.