adding a new route to node express adding a new route to node express express express

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 insideroutes = 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 });};


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.


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 routerouter.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){  }}