Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express 4 router with external file

I have the following files

lib/pub
lib/pub/index.js
app.js

On App.js

I have:

// app.js
var express = require("express")
, app = express()
, router = express.Router()
;
... 
router.use('/pub',require('./pub'));

and then on index.js

// pub/index.js
var express  = require('express')
, router = express.Router()
;
console.log("file loaded successfully")
module.exports = function(){
  router.get('/',function(req,res){
     console.log("got the get request")
  })
}

The problem I have when I do localhost/pub request, I never get the got the get request, no matter whatever I try to change the code around, trying to add pub to the path.

router.get('/',...
router.get('/pub',...
router.get('./pub,...
router.get('./',...
router.get('pub',...
etc...

None of those or any other silly way I have attempted work... I can never get the log to say yes I got the request...

What am I doing wrong ! (expressjs changes so frequently and radically, any web tutorials become redundant or any previous help others got)

like image 613
Val Avatar asked Dec 11 '22 06:12

Val


1 Answers

(edited to reflect comments)

If you want to move your routes to an external file, use the following pattern:

app.js

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

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

routes.js

module.exports = function(app) {
  app.get('/pub', function(req, res) {
    console.log('got the get!');
    res.end();
  });
};
like image 161
SomeKittens Avatar answered Dec 22 '22 00:12

SomeKittens