使用Node. js/ Express进行数千次路由

mlmc2os5  于 2023-01-12  发布在  Node.js
关注(0)|答案(1)|浏览(108)

我正在学习Node. js/ Express。
我知道如何使用路由器与类似的东西:

const productsRouter = require('./routes/products');
const employeesRouter = require('./routes/employees');

app.use('/products', productsRouter);
app.use('/employees', employeesRouter);

我想知道,如何处理十几个路由。我不谈网址参数,只是路由。
我应该创建几十个模块吗?并且把上面的行复制几十次吗?有没有更优雅简洁的解决方案?

iszxjhcz

iszxjhcz1#

you can group all your routes in the routes folder

    |-- app.js
    |-- routes
    |   |-- index.js
    |   |-- router1.js
    |   |-- router2.js
    |   |-- routes.js

in routes.js import all the routes 

 
 
   module.exports = function(app) {
  app.use(express.json());

  app.use("/", indexRouter);
  app.use("/router1", router1Router);
  app.use("/router2", router2Router);
};



And in App.js only import routes.js:

 
 
     const express = require("express");
    const app = express();
    require("./startup/routes")(app);

相关问题