Instagram
youtube
Facebook
Twitter

ExpressJS- Routing

ExpressJS - Routing

  • Routing refers to how an application's URLs respond to a user request.
  • It can manage different types of HTTP requests.
  • The function defines routes in an express application:
app.method(path,handler)
  • the method here is any one of the HTTP verbs- get, put, post, and delete.
  • the path is route.
  • handler is call back function.

Example:

In index.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 CodersDaily!');  
})  
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)  
})  

Run the server by command on the terminal:

node index.js

In URL: http://localhost:8000/

In URL: http://localhost:8000/enrolled_student

In URL:http://localhost:8000/ab*cd