Express.js Routing

Routing is made from the word route. It is used to determine the specific behavior of an application. It specifies how an application responds to a client request to a particular route, URI or path and a specific HTTP request method (GET, POST, etc.). It can handle different types of HTTP requests.

Let's take an example to see basic routing.

File: routing_example.js

snippet
var express = require('express');
var app = express();
app.get('/', function (req, res) {
   console.log("Got a GET request for the homepage");
   res.send('Welcome to rookienerd!');
})
app.post('/', function (req, res) {
   console.log("Got a POST request for the homepage");
   res.send('I am Impossible! ');
})
app.delete('/del_student', function (req, res) {
   console.log("Got a DELETE request for /del_student");
   res.send('I am Deleted!');
})
app.get('/enrolled_student', function (req, res) {
   console.log("Got a GET request for /enrolled_student");
   res.send('I am an enrolled student.');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {   
   console.log("Got a GET request for /ab*cd");
   res.send('Pattern Matched.');
})
var server = app.listen(8000, function () {
var host = server.address().address
  var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
ExpressJS Routing

You see that server is listening.

Now, you can see the result generated by server on the local host http://127.0.0.1:8000

Output:

This is the homepage of the example app.

ExpressJS Routing

Note: The Command Prompt will be updated after one successful response.

ExpressJS Routing

You can see the different pages by changing routes. http://127.0.0.1:8000/enrolled_student

ExpressJS Routing

Updated command prompt:

ExpressJS Routing

This can read the pattern like abcd, abxcd, ab123cd, and so on.

Next route http://127.0.0.1:8000/abcd

ExpressJS Routing

Next route http://127.0.0.1:8000/ab12345cd

ExpressJS Routing

Updated command prompt:

ExpressJS Routing
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +