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
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) })
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.
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
Updated command prompt:
This can read the pattern like abcd, abxcd, ab123cd, and so on.
Next route http://127.0.0.1:8000/abcd
Next route http://127.0.0.1:8000/ab12345cd
Updated command prompt: