Separating Routes In Node.js Express 4

By Budyks    NodeJs

Please Kindly Share To Your Social Media

If you just upgraded your Express version to 4.* you will find a lot of differences. The most important stuff added to version 4 is  Router API that provides us a Flexible Routing and RESTful. In any nodejs project, putting all the routes and its code inside server.js / app is terrible.

Here's the easy way to separate Routes in Express 4 . 

Suppose you've created a fresh express 4 (check here for installation ) . Now lets coding .

by the way your folder structure should be like this 

-project--node_modules--routes ----index.js--server.js

see that red things, create them yourself. 


var express  = require('express'),    app = express();/*    Your middlewares or setups usually around here*///API Routervar router = express.Router();// calling the outside routes var index = require('./routes/index').router;app.use('/',index);//start Servervar server = app.listen(3000,function(){    console.log("Listening to port %s",server.address().port);});


var express = require('express');var router = express.Router();router.get('/',function(req,res){        res.send("Welcome to Node JS");});router.get('/about',function(req,res){        res.send("This is About page");});/*RESTful API Router*/var api = router.route('/api/v1/user');//middleware api api.all(function(req,res,next){        /*Do stuffs here when a call to api route invoked*/    console.log(req.method,req.url);    next();});//GET verbapi.get(function(req,res){        //Do stuffs here...    res.send("Get list user ...");});//POST,res){        //Do stuffs here...    res.send("Post a user ...");});//PUT verbapi.put(function(req,res){     //Do stuffs here...    res.send("Edit / modify a user ...");});//DELETE verbapi.delete(function(req,res){        //Do stuffs here...    res.send("Delete a user ...");});//this line is the Mastermodule.exports.router = router;

Now run your project 

node server.js

Fire in your browser 




    Follow Us