在我的NodeJS express应用程序中,我有app.js,它有一些常见的路由。然后在wf.js文件中,我想定义更多的路由。

如何让app.js识别在wf.js文件中定义的其他路由处理程序?

一个简单的要求似乎不起作用。


当前回答

如果你使用express-4。使用TypeScript和ES6,这将是最好的模板使用:

登录src /火/ ts。

import express, { Router, Request, Response } from "express";

const router: Router = express.Router();
// POST /user/signin
router.post('/signin', async (req: Request, res: Response) => {
    try {
        res.send('OK');
    } catch (e) {
        res.status(500).send(e.toString());
    }
});

export default router;

src / app.ts

import express, { Request, Response } from "express";
import compression from "compression";  // compresses requests
import expressValidator from "express-validator";
import bodyParser from "body-parser";
import login from './api/login';

const app = express();

app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());

app.get('/public/hc', (req: Request, res: Response) => {
  res.send('OK');
});

app.use('/user', login);

app.listen(8080, () => {
    console.log("Press CTRL-C to stop\n");
});

比使用var和module.exports干净多了。

其他回答

所有这些答案的一个调整:

var routes = fs.readdirSync('routes')
      .filter(function(v){
         return (/.js$/).test(v);
      });

只需使用正则表达式通过测试数组中的每个文件进行筛选。它不是递归的,但它会过滤掉不以.js结尾的文件夹

我知道这是一个老问题,但我一直在为自己寻找答案,而这就是我最后的归宿,所以我想把我的解决方案用在类似的问题上,以防别人有和我一样的问题。有一个很好的节点模块叫做委托,它为你做了很多文件系统的东西,在这里看到(即没有readdirSync的东西)。例如:

我有一个restful API应用程序,我试图构建,我想把所有的请求,去'/ API /*'进行身份验证,我想存储所有的路由,在API到他们自己的目录(让我们只是叫它' API ')。在应用程序的主要部分:

app.use('/api', [authenticationMiddlewareFunction], require('./routes/api'));

在routes目录中,我有一个名为“api”的目录和一个名为api.js的文件。在api.js中,我简单地有:

var express = require('express');
var router = express.Router();
var consign = require('consign');

// get all routes inside the api directory and attach them to the api router
// all of these routes should be behind authorization
consign({cwd: 'routes'})
  .include('api')
  .into(router);

module.exports = router;

一切都按照预期进行。希望这能帮助到一些人。

如果你想把路由放在一个单独的文件中,例如routes.js,你可以这样创建routes.js文件:

module.exports = function(app){

    app.get('/login', function(req, res){
        res.render('login', {
            title: 'Express Login'
        });
    });

    //other routes..
}

然后你可以从app.js中以这样的方式传递app对象:

require('./routes')(app);

看看这些例子:https://github.com/visionmedia/express/tree/master/examples/route-separation

您可以将所有路由函数放在其他文件(模块)中,并将其链接到主服务器文件。 在main express文件中,添加一个将模块链接到服务器的函数:

   function link_routes(app, route_collection){
       route_collection['get'].forEach(route => app.get(route.path, route.func));
       route_collection['post'].forEach(route => app.post(route.path, route.func));
       route_collection['delete'].forEach(route => app.delete(route.path, route.func));
       route_collection['put'].forEach(route => app.put(route.path, route.func));
   }

并为每个路由模型调用该函数:

link_routes(app, require('./login.js'))

在模块文件(例如- login.js文件)中,像往常一样定义函数:

const login_screen = (req, res) => {
    res.sendFile(`${__dirname}/pages/login.html`);
};

const forgot_password = (req, res) => {
    console.log('we will reset the password here')
}

然后用request方法导出它作为键,值是一个对象数组,每个对象都有路径和功能键。

module.exports = {
   get: [{path:'/',func:login_screen}, {...} ],
   post: [{path:'/login:forgotPassword', func:forgot_password}]
};   

我试图用“express”更新这个答案:“^4.16.3”。这个答案与ShortRound1911的答案相似。

server.js:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const db = require('./src/config/db');
const routes = require('./src/routes');
const port = 3001;

const app = new express();

//...use body-parser
app.use(bodyParser.urlencoded({ extended: true }));

//...fire connection
mongoose.connect(db.url, (err, database) => {
  if (err) return console.log(err);

  //...fire the routes
  app.use('/', routes);

  app.listen(port, () => {
    console.log('we are live on ' + port);
  });
});

/ src /线路/ index.js:

const express = require('express');
const app = express();

const siswaRoute = require('./siswa_route');

app.get('/', (req, res) => {
  res.json({item: 'Welcome ini separated page...'});
})
.use('/siswa', siswaRoute);

module.exports = app;

/ src /线路/ siswa_route.js:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.json({item: 'Siswa page...'});
});

module.exports = app;