Monday, 3 July 2017

Express Js routing example - GET/POST/PUT

Express JS Routing - Understanding GET/POST/PUT with parameter

Question: Give example of express JS working with Node?
var express = require('express');
var app = express();

var bodyParser = require('body-parser')
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({
    extended: true
}));

app.get('/', function(req, res){
  res.send('id: ' + req.query.id);  
});
app.listen(3000);



Question: What is use of body-parser?
It is middleware in nodeJS.
body-parser is used to parse incoming request bodies, available under the req.body property.



Example-1: URL / with Get Method.
app.get('/', function (req, res) {
  res.send('Hello, this is Home page.')
})



Example-2: URL /about with Get Method.
app.get('/about', function (req, res) {
  res.send('You have called /about with get method.')
})



Example-3. URL /senddata with POST Method.
app.post('/senddata', function (req, res) {
    //req.body have all the parameter
   console.log(req.body);
  res.send('Hello, Received post data request.')
})



Example-4: Routing with Regex 
app.get('/ab?cd', function (req, res) {
  res.send('ab?cd')
})

This route path will match acd, abcd.


Example-5: Routing with Regex
app.get('/ab+cd', function (req, res) {
  res.send('ab?cd')
})
This route path will match abcd, abbcd, abbbcd, and so on.



Example-6: Routing with dynamic parameter 
app.get('/users/:userId/books/:bookId', function (req, res) {
  console.log(req.params);
   res.send('Received the request for /users/10/book/12222');
});

Request URL: http://localhost:8080/users/10/books/12222


Example-7: Routing with dynamic parameter - Example 2
app.get('/messages/:from-:to', function (req, res) {
  console.log(req.params);
   res.send('Received the request for /messages/10-100');
});

Request URL: http://localhost:8080/messages/10-1000


Question: How to send request with all methods i.e GET/POST/PUT
app.all('/messages/list', function (req, res) {  
   res.send('Work for all type of request');
});