使用express.js动态加载路由

时间:2013-05-28 04:57:00

标签: node.js express routes

我使用express.js作为网络服务器,想要一种简单的方法将所有“app.get”和“app.post”功能分开来分隔文件。例如,如果我想为登录页面指定get和post函数,我想在一个动态加载的routes文件夹中有一个login.js文件(将自动添加所有文件而不必指定每个文件) )当我运行节点app.js

我试过这个this solution!,但它对我不起作用。

4 个答案:

答案 0 :(得分:16)

app.js

var express=require("express");
var app=express();
var fs=require("fs");
var routePath="./routers/"; //add one folder then put your route files there my router folder name is routers
fs.readdirSync(routePath).forEach(function(file) {
    var route=routePath+file;
    require(route)(app);
});
app.listen(9123);

我在该文件夹中放置了两个路由器

route1.js

module.exports=function(app){
  app.get('/',function(req,res){
     res.send('/ called successfully...');
  });
}

route2.js

module.exports=function(app){
app.get('/upload',function(req,res){
  res.send('/upload called successfully...');
});
}

答案 1 :(得分:0)

我最终使用递归方法来保持代码可读和异步:

// routes     
processRoutePath(__dirname + "/routes");

function processRoutePath(route_path) {
    fs.readdirSync(route_path).forEach(function(file) {
        var filepath = route_path + '/' + file;
        fs.stat(filepath, function(err,stat) {
            if (stat.isDirectory()) {
                processRoutePath(filepath);
            } else {
                console.info('Loading route: ' + filepath);
                require(filepath)(app, passport);
            }
        });
    });
}

通过检查正确的文件扩展名等可以使这更加健壮,但我保持路线文件夹清洁,不希望增加复杂性

答案 2 :(得分:0)

使用这种方法,无需手动编写路由。只需设置一个像URL路径一样的目录结构。示例路由位于/routes/user/table/table.get.js,API路由为/user/table

import app from './app'
import fs from 'fs-readdir-recursive'
import each from 'lodash/each'
import nth from 'lodash/nth'
import join from 'lodash/join'
import initial from 'lodash/initial'

const routes = fs(`${__dirname}/routes`)
each(routes, route => {
  let paths = route.split('/')

  // An entity has several HTTP verbs
  let entity = `/api/${join(initial(paths), '/')}`
  // The action contains a HTTP verb
  let action = nth(paths, -1)

  // Remove the last element to correctly apply action
  paths.pop()
  action = `./routes/${join(paths, '/')}/${action.slice(0, -3)}`

  app.use(entity, require(action))
})

示例路线:

import { Router } from 'express'
import Table from '@models/table.model'

const routes = Router()

routes.get('/', (req, res, next) => {   
  Table
    .find({user: userIdentifier})
    .select('-user')
    .lean()
    .then(table => res.json(table))
    .catch(error => next(error))
})

module.exports = routes

答案 3 :(得分:0)

打字稿

路由/testroute.ts

import { Router } from 'express';

const router = Router();
router.get('/test',() => {
    // Do your stuffs Here
});



export = router;

index.ts

let app = express() 

const routePath = path.join(__dirname, 'routes');

fs.readdirSync(routePath).forEach(async (filename) => {
    let route = path.join(routePath, filename);
    try {
        const item = await import(route);
        app.use('/api', item.default);
    } catch (error) {
        console.log(error.message);
    }
});

app.listen()