yooouuri
yooouuri

Reputation: 2658

Require with parameter

I want to seperate my routes from the app.js file.

The login route need a firebase instance.

routes/auth.js

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

module.exports = function(firebase) {
    ...
}

module.exports = router;

app.js

var firebase = require('firebase');

var config = {
    ...
}

firebase.initializeApp(config);

var auth = require('./routes/auth')(firebase)

app.use('/admin', auth)

When i start the server, it gives me a TypeError: Cannot read property 'indexOf' of undefined error...

It points to the require statement in app.js:

var auth = require('./routes/auth')(firebase)


Edit:

When i try to access /auth it given me a Cannot GET /auth error..

app.js

const PORT = 8081

...

var auth = require('./routes/auth')(firebase)

app.use('/auth', auth)

app.listen(PORT, function () {
  console.log(util.format('Example app listening on port %d!', PORT))
})

routes/auth.js

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

module.exports = function(firebase) {
  router.get('/auth', function(req, res) {
    res.send('hi')
  })

  return router
}

The url im trying to access is http://localhost:8081/auth

Upvotes: 1

Views: 141

Answers (1)

Keith
Keith

Reputation: 24181

For the first problem..

Your auth.js, has 2 exports.. So your last export will win. I think what your after is more like -> module.exports = function(firebase) { return router; }

The second problem was that your using app.use(url, obj).. The url you provide will become the root node of your middleware.. So when you did router.get(url, callback), what's then happening is the the url will become /aut/auth

2 options here,

  1. Don't supply a root, eg. app.use(auth)
  2. Remove the url from your get, as it's already been set from app.use, so router.get('/', callback)

Upvotes: 2

Related Questions