bipin
bipin

Reputation: 419

app.use not working in other class express

i m try to use app instance in other js file but don't know why it not working, below is sample code (i m using express 4)

app.js

    const app = express();
    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

    const bodyParser = require('body-parser')
    const jsonParser = bodyParser.json({ limit: '10mb' }) //{
    const urlEncoded = bodyParser.urlencoded({ limit: '10mb', extended: true }) //

    app.set('superSecret', config.secret)
    app.disable("x-powered-by")
  //oauth file
   var oauth= require('./services/oauth');

    module.exports = app

in service/oauth file index.js

 module.export.oauth2app=oauth2app
  const oauth2app =require('../../app')
  oauth2app.use('/',router);  //its not working

why oauth2app.use not working in index.js it throw error like oauth2app.use is not function can any body tell me what i m doing wrong

Upvotes: 0

Views: 61

Answers (1)

jfriend00
jfriend00

Reputation: 708116

You have a circular dependency. app.js is loading service/oauth/index.js and then that file is attempted to load app. You can't do that. The second one that causes the circular loop will return {} and thus {}.use() won't work.

The usual solution here is to pass the app object to your service/oauth/index.js module in an exported module constructor function rather than have it try to load app.

    const app = express();
    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

    const bodyParser = require('body-parser')
    const jsonParser = bodyParser.json({ limit: '10mb' }) //{
    const urlEncoded = bodyParser.urlencoded({ limit: '10mb', extended: true }) //

    app.set('superSecret', config.secret)
    app.disable("x-powered-by")

    // oauth file 
    // pass app to module constructor function
    require('./services/oauth')(app);

And, then in the oauth file, you export a function that is used to initialize the module:

// this should get called by whoever loads us and they should
// pass us the app object.
module.exports = function(app) {
      app.use('/', router);
}

Upvotes: 3

Related Questions