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

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

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


当前回答

您可以将所有路由函数放在其他文件(模块)中,并将其链接到主服务器文件。 在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}]
};   

其他回答

您可以将所有路由函数放在其他文件(模块)中,并将其链接到主服务器文件。 在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}]
};   

我写了一个小插件来做这件事!我厌倦了一遍又一遍地写同样的代码。

https://www.npmjs.com/package/js-file-req

希望能有所帮助。

如果你使用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干净多了。

在快车4号。X,你可以得到一个路由器对象的实例,并导入另一个包含更多路由的文件。您甚至可以递归地执行此操作,以便您的路由导入其他路由,从而允许您创建易于维护的URL路径。

例如,如果我的/tests端点已经有一个单独的路由文件,并且想为/tests/automated添加一组新的路由,我可能想将这些/automated路由分解到另一个文件中,以保持/test文件小且易于管理。它还可以让你在逻辑上把路由按URL路径组合在一起,这非常方便。

./app.js的内容:

var express = require('express'),
    app = express();

var testRoutes = require('./routes/tests');

// Import my test routes into the path '/test'
app.use('/tests', testRoutes);

./routes/tests.js的内容:

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

var automatedRoutes = require('./testRoutes/automated');

router
  // Add a binding to handle '/tests'
  .get('/', function(){
    // render the /tests view
  })

  // Import my automated routes into the path '/tests/automated'
  // This works because we're already within the '/tests' route 
  // so we're simply appending more routes to the '/tests' endpoint
  .use('/automated', automatedRoutes);
 
module.exports = router;

./routes/testRoutes/ automatic .js文件的内容:

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

router
   // Add a binding for '/tests/automated/'
  .get('/', function(){
    // render the /tests/automated view
  })

module.exports = router;

如果你想要一个单独的.js文件来更好地组织你的路由,只需在app.js文件中创建一个变量,指向它在文件系统中的位置:

var wf = require(./routes/wf);

然后,

app.get('/wf', wf.foo );

其中.foo是wf.js文件中声明的某个函数。如

// wf.js file 
exports.foo = function(req,res){

          console.log(` request object is ${req}, response object is ${res} `);

}