Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

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

  1. var express = require(‘express’);
  2. var app = express();
  3. app.get(‘/’, function (req, res) {
  4.    console.log(“Got a GET request for the homepage”);
  5.    res.send(‘Welcome to Kreationnext!’);
  6. })
  7. app.post(‘/’, function (req, res) {
  8.    console.log(“Got a POST request for the homepage”);
  9.    res.send(‘I am Impossible! ‘);
  10. })
  11. app.delete(‘/del_student’, function (req, res) {
  12.    console.log(“Got a DELETE request for /del_student”);
  13.    res.send(‘I am Deleted!’);
  14. })
  15. app.get(‘/enrolled_student’, function (req, res) {
  16.    console.log(“Got a GET request for /enrolled_student”);
  17.    res.send(‘I am an enrolled student.’);
  18. })
  19. // This responds a GET request for abcd, abxcd, ab123cd, and so on
  20. app.get(‘/ab*cd’, function(req, res) {
  21.    console.log(“Got a GET request for /ab*cd”);
  22.    res.send(‘Pattern Matched.’);
  23. })
  24. var server = app.listen(8000, function () {
  25. var host = server.address().address
  26.   var port = server.address().port
  27. console.log(“Example app listening at http://%s:%s”, host, port)
  28. })

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.

expressjsrouting2

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

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

expressjsrouting4

Updated command prompt:

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

Next route http://127.0.0.1:8000/abcd

expressjsrouting6

Next route http://127.0.0.1:8000/ab12345cd

expressjsrouting7

Updated command prompt:

expressjsrouting8

 

Comments

comments