Separating Routes In Node.js Express 4
|Shares :

Separating Routes In Node.js Express 4

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. 

server.js

var express  = require('express'),
    app = express();
/*
    Your middlewares or setups usually around here
*/
//API Router
var router = express.Router();// calling the outside routes
var index = require('./routes/index').router;
app.use('/',index);

//start Server
var server = app.listen(3000,function(){
 
   console.log("Listening to port %s",server.address().port);
});


routes/index.js

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 verb
api.get(function(req,res){
    
    //Do stuffs here...
    res.send("Get list user ...");
});
//POST verb
api.post(function(req,res){
    
    //Do stuffs here...
    res.send("Post a user ...");
});
//PUT verb
api.put(function(req,res){
     //Do stuffs here...
    res.send("Edit / modify a user ...");
});
//DELETE verb
api.delete(function(req,res){
    
    //Do stuffs here...
    res.send("Delete a user ...");
});
//this line is the Master
module.exports.router = router;

Now run your project 

node server.js

Fire in your browser 

localhost:3000
localhost:3000/about
localhost:3000/api/v1/user

Cheerss!!!!

Tags : #nodejs #restful #api #mysql #crud #source #code


SHARES :


Budy K's Avatar

Sains & Teknologi Enthusiast, Software Developer. Check my profile!
> 75% komen akan dibalas. Mohon sabar ya. Simpan halaman ini dan cek kembali lagi

Comments

* Email will not be published


    Privacy .ToS .Contact Us
    © 2017 Teknosains