简体   繁体   中英

Express.js - Import routes into subroute

I'm trying to build an modular express.js server with a good structure. Tryed to use the different routes as the components in react.

index.js

var syncsingle = require('./XYZ/syncsingle');
app.get('/sync', syncsingle);

syncsingle.js

if ( ** cool things **){
    var one = require ('./XYZ/sync/one');
    app.use('/sync', one);
}else{
    var two = require ('./XYZ/sync/two');
    app.use('/sync', two);
}

Maybe someone could help me out with that issue? The code which is written in one.js and two.js should be just imported/included at the app.use(..) point. (eg in PHP the include('blaa.php') thing).

Thank you very much <3

Try passing the middleware or sub-app directly to your main app.

// index.js
var sync = require("./syncsingle.js")
app.use("/sync", sync)

// syncsingle.js
if ( ** cool things **){
  module.exports = require ('./XYZ/sync/one');
} else {
  module.exports = require ('./XYZ/sync/two');
}

It's also common to pass configuration to sub-apps or middleware.

var one = require ('./XYZ/sync/one');
var two = require ('./XYZ/sync/two');

module.exports = function sync(options) {
  if ( ** cool things based on options ** ){
    return one;
  else {
    return two;
  }
}

In your main app file:

app.use("/sync", sync({ useOne: true })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM