How to use multiple router files - node.js

How do I use multiple router files using express framework?
In my app.js, I have the following code:
var controller = require('./controller/index');
var healthController = require('./controller/health/');
app.use('/', controller);
app.use('/health', healthController);
And controller/index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
And health.js:
var express = require('express');
var router = express.Router();
/* GET health confirmation. */
router.get('/health', function(req, res, next) {
res.send('OK');
});
module.exports = router;
When I hit the http://localhost:8000/, I get the correct page without any problem, however, http://localhost:8000/health results in 404 error.
Thanks in advance.

Assuming the "health.js" resides in "controller" directory, may it be just a typo issue? var healthController = require('./controller/health/'); has a trailing slash (/). Removing it would fly? So it becomes var healthController = require('./controller/health');

Your single node app must have single router object, a router object represents a server in express requiring unique port.
Hence you should create router object in you app.js passing it to all router files.
Code will be like -
app.js
var express = require('express');
var router = express.Router();
var controller = require('./controller/index');
var healthController = require('./controller/health/');
controller(router);
healthController(router);
index.js
module.exports = function(router) {
router.get('/', function(req, res, next) {
res.render('index');
});
}
health.js
module.exports = funtion(router) {
router.get('/health', function(req, res, next) {
res.send('OK');
});
}

See How to include route handlers in multiple files in Express?.
Export an anonymous function that can be "initiated" with a reference to the original express app.
./controller/index.js:
module.exports = function(app) {
/* GET home page. */
app.get('/', function(req, res, next) {
res.render('index');
});
};
./controller/health.js:
module.exports = function(app) {
/* GET health confirmation. */
app.get('/health', function(req, res, next) {
res.send('OK');
});
};
./app.js:
var app = require('express')();
var controller = require('./controller/index');
var healthController = require('./controller/health');
controller(app);
healthController(app);

Change in health.js:
router.get('/health', function(req, res, next) {
res.send('`OK`');
});
to
router.get('/', function(req, res, next) {
res.send('OK');
});
This will work fine check it out.

Related

What does a wildcard route do in express.js?

So, I have these routes in my app.js file.
app.use("/api/v1/users", userRouter)
app.use("/*", indexRouter)
And in index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/*', function(req, res, next) {
res.render('index', { title: 'Gratitude Journal App' });
});
module.exports = router;
What does the * do exactly?
It will render index page for all of your app's GET request. It (*) will match any string(route) after it.

How can I separate route files?

I have a route file in my project and it is called from my app with these lines:
var index = require('./routes/index');
app.use('/', index);
But I need to separate the route file, and I'm trying to do this:
var index = require('./routes/index');
var user = require('./routes/user');
app.use('/', index);
app.use('/user', user);
In route user.js I put the service that I need to access from the client. But it's not working. I don't know what is wrong, I am a beginner in Node.js.
The request returns:
GET /user/find 304 4.203 ms - -
And user.js file is:
var router = express.Router();
router.get('/user/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
*This request works well on index.js
You put user router under /user route, and in your user router you defined app.get('/user/find'), so the actual path would be /user/user/find, you need to remove the user prefix in router
var router = express.Router();
router.get('/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
A simple way to do this can be:
index.js
var express = require('express')
var app = express()
var route1 = require('./route1')
var route2 = require('./route2')
app.use('/', route1);
app.use('/hello', route2);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
route1.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route1');
})
module.exports = router
route2.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route2');
})
module.exports = router
Have you made sure to include a module.exports = router at the end of each of your route files?
Your route files should be set up thusly:
var router = require('express').Router();
router.get("/example", function (req, res) {
res.send("Hello");
});
module.exports = router;

sharing an object between app.js and routes y node.js

This is my app.js
var express = require('express');
...
var model = require('./models/my_model');
var routes = require('./routes/index');
var app = express();
app.use('/', routes);
var middlewareBefore = function(req, res, next){
my_model.getName(function(err, result){
if(err){
console.log(err);
res.redirect('/error');
}else{
console.log(result);
next();
}
})
}
app.use(middlewareBefore);
...
module.exports = app;
and this is my routes/index.js file
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('login', { url: my_model.getUrl() });
});
module.exports = router();
I'm trying to access my_model from the route file. I've already tried using app.locals, res, req, res.locals and app.use('/', routes)(my_model), as seen on different questions from this page, but none of them seem to work... I wonder if the usage of express.Router() is creating this issue (note that setting the middleware before the route didn't solve this)
Several ways to do that:
1.use app.use('/', routes); after declaration of middlewareBefore variable.
2.or declare my_model directly in routes/index.js at top var model = require('./models/my_model');
and use within router.get().
3.or better use MVC architecture.

404 on routing with nginx and expressjs

i have created on EC2 an instance of ubuntu server and trying to get the express generator simple skeleton get working.
when i go to root http://MY_SERVER_IP_HERE/ the index page of the app is shown.
if i go to http://MY_SERVER_IP_HERE/users im getting 404 even though the express app is set up to handle this route.
var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);
/routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
/**** WORKS FINE ****/
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
/routes/users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
/*** GETTING 404 ****/
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
my nginx routing settings:
location ~ ^/(stylesheets/|css/|js/){
root /var/www/html/test/myapp/public;
}
location / {
proxy_pass http://MY_SERVER_IP:3000;
}
thank you very much!
Change the code like this.
server.js
var express= require('express');
var app = express();
require('./routes/index')(app, express);
require('./routes/users')(app, express);
//.....
app.listen(3000);
/routes/index.js
module.exports = function(app, express) {
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
app.use('/', router);
};
/routes/users.js
module.exports = function(app, express) {
var router = express.Router();
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
app.use('/users', router);
};

How to call express 4.0 middleware function in app.js from router?

I have a middleware function to do the basic authorization which is in app.js (starter javascript). But there are a few router files in other javascript files. My question is how I can call the authorization middleware function in my router?
Here is my app.js:
var basicAuth = require('basic-auth');
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'foo' && user.pass === 'bar') {
return next();
} else {
return unauthorized(res);
};
};
module.exports = app;
My router file index.js:
var express = require('express');
var router = express.Router();
router.get('/', auth, function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Apparently the auth is not defined here. Can anybody tell me how can I use auth middleware function in my index.js router functions? Thanks
I'm not sure exactly what you're attempting to export with.
module.exports = app;
in app.js
Here is a simplifed solution:
index.js
var express = require('express');
var app = express();
var auth = require('./auth');
var router = express.Router();
router.use(auth); // Auth middleware is first
router.get('/', function(req, res) {
return res.send('Hello world');
}
// More routes can go here
// require('./external')(router);
// router.get('/route', function(req, res) {}
app.use(router);
app.listen(3000);
auth.js
module.exports = function(req, res, next) {
return next();
}
If you have routes in other files you can either pass app or router
external.js
module.exports = function(router) {
}
Why not put your auth middleware in a separate file that you can require() and use from both app.js and your router files?

Resources