7

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

我已经尝试过这个解决方案!但它对我不起作用。

4

4 回答 4

17

应用程序.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...');
});
}
于 2013-05-28T06:22:37.010 回答
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);
            }
        });
    });
}

这可以通过检查正确的文件扩展名等来变得更加健壮,但是我保持我的路由文件夹干净并且不希望增加复杂性

于 2015-09-11T22:41:27.800 回答
0

打字稿

路线/testroute.ts

import { Router } from 'express';

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



export = router;

索引.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()

于 2021-06-01T14:33:11.007 回答
-2

使用这种方法,无需手动编写路由。只需设置一个目录结构,如 URL 路径。示例路线是 at/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
于 2018-02-08T07:58:56.353 回答