a blog for those who code

Tuesday, 12 January 2016

Basic Routing in Express

In this post we will discuss about Basic Routing in Express. In simple terms routing is a mechanism to handle the request coming from client, processing the request and sending the response back to client. Thus it helps us the application to decide how to respond to a client request to a particular endpoint. In Express it is very easy to handler the router of your app.


Basic Routing : Below code is the example of basic routing in Express. The below code will print "Hello World Express" when you access the homepage of your application.

app.get('/', function(req, res) {
  res.send('Hello World Express');
});

Now we will change our code to route to some static page (lets say about page).

app.get('/about', function(req, res) {
  res.send('About CodingDefined.com');
});

'/', '/about', '/home' are called Route Paths. So Route Paths along with request method (get, post etc) defines the endpoints at which request can be made.

The above Route Paths are all static paths where you defined the set of pages beforehand, what if we want the dynamic routes. For that we will change our code to something as shown below. In the below code whatever id I give it just fetches that id using request object (req) and displays it to the user.

app.get('/id/:id', function(req, res) {
  res.send("You queried for " + req.params.id);
});

Similar to GET HTTP methods we do have POST, PUT, DELETE in Express which can be used as shown below :

app.post('/login', function(req, res) {
   //Can take username and password for authentication
});

app.put('/user/:id', function(req, res) {
   //Edit the user with id - :id 
});

app.delete(/user/:id, function(req, res) {
   //Delete the user with id - :id
});

Serving Static Folder

Now if I want my entire folder which has some images, some text files to be served directly without writing route for each and every files then that can be done using the below code.

app.use(express.static(path.join(__dirname, 'public')));

Connect module which is a dependency of Express web framework takes care of this. The above code will set the public directory to be visible over the server without writing the routes for each one of them.

In the below video you will be able to see the working of Basic Routing in Express.

Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License