adding a new route to node express
The trouble is:
routes = require('./routes'),
user = require('./routes/user'),
furniture = require('./routes/furniture'),
These 3 are setting your routes folders, not a specific file, express will look for a index.js ( not found, then --> error)
Inside these folders, you should put a index.js with your:
exports.xxxx = function(req, res){
res.render('xx', { foo: foo});
};
Then, your project folder structure should look like:
routes/
├── index.js
│
├── user/
│ └── index.js (with a exports.user inside)
│
└── fourniture/
└── index.js (with a exports.furniture inside)
You can add multiple export functions to a route like these:
app.js
// a folder called routes with the index.js file inside
routes = require('./routes')
.
.
.
app.get('/', routes.main_function);
app.get('/sec_route', routes.sec_function);
app.post('/other_route', routes.other_function);
/routes/index.js
exports.main_function = function(req, res){
res.render('template1', { foo: foo });
};
exports.sec_function = function(req, res){
res.render('template2', { bar: bar });
};
exports.other_function = function(req, res){
res.render('template1', { baz: baz });
};
Follow a simple and consistent folder structure, then use a module to have everything done automatically.
Then never look back. Spend time saved on the rest of the important stuff.
TL;DR
$ npm install express-routemagic --save
const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')
That's it!
More info:
How you would do this? Let's start with file structuring:
project_folder
|--- routes
| |--- nested-folder
| | |--- index.js
| |--- a-file-that-doesnt-share-same-name-with-another-folder.js
| |--- index.js
|--- app.js
In app.js
const express = require('express')
const app = express()
const magic = require('express-routemagic')
magic.use(app, __dirname, 'routes')
In any of your routing files:
For e.g., index.js
const router = require('express').Router()
router.get('/', (req, res) => { ... })
router.get('/something-else', (req, res) => { ... })
Or a-file-that-doesnt-share-same-name-with-another-folder.js
Usually you might want to start a folder and use the
index.js
pattern. But if it's a small file it's okay.
const router = require('express').Router()
const dir = 'a-file-that-do-not-have-another-folder-with-same-name' // you can use this to shorten, but it's optional.
router.get(`$(dir)/`, (req, res) => { ... })
router.get(`$(dir)/nested-route`, (req, res) => { ... })
Disclaimer: I wrote the package. But really it's long-overdue, it reached my limit to wait for someone to write it.
Although this is somewhat old, though of sharing the way i do this. Here is a another approach which makes code more cleaner and easy to add routes.
app.js
const app = express();
const routes = require('./routes');
app.use('/api', routes); //Main entry point
/routes/index.js
const router = require('express').Router();
const user = require('./user');
const admin = require('./admin');
//This is a simple route
router.get('/health-check', (req, res) =>
res.send('OK')
);
router.route('/users')
.post(validate, user.createUser);
router.route('/users/:userId')
.get(validateUser, user.getUser)
.patch(validateUser, user.updateUser)
.delete(validateUser, user.deleteUser);
router.route('/admins/:adminId/dashboard')
.get(validateAdmin,admin.getDashboard);
module.exports = router;
'validateUser' and 'validateAdmin' are custom middle wares, which will be used to validates request parameters or to do some pre-processing before request reach the actual request handler. This is optional and you can have multiple middleware (comma separated) as well.
/routes/user.js
module.exports = {
createUser:function(req,res,next){
},
updateUser:function(req,res,next){
},
deleteUser:function(req,res,next){
}
}
/routes/admin.js
module.exports = {
getDashboard:function(req,res,next){
}
}
If your website is so big some times I prefer to do something like:
routes/furniture.js
:
module.exports = function(app)
{
app.get("/furniture/", function(req, res) {
res.render('furniture', { title: '4\267plieee' });
});
}
And then in app.js
:
require("./routes/furniture")(app);
It's mainly the same but app.js will be cleaner.