REST stands for “Representable and is an architecture style that is often used in the development of Web Services. REST Services use HTTP protocols to communicate. In REST Services, every component is a resource and accessed by common HTTP protocol. In REST, the Services are following the components, that are used.
GET
Provide readily access to the resource.
POST
Update the resource.
PUT
Create a new resource.
DELETE
Delete the existing resource.
In most of cases, GET and POST methods are generally used. When we send a GET request to the Server, then this request contains request parameters and cookies data in the header section.
Example
GET /? id=10 & name= Pankaj HTTP 1.1
Host
www.google.com
Cookies
username Pankaj
Whenever a Browser generates a request, then it inserts the query string in request header and at Server, we need to fetch out the data from the query string. In case of POST method, the data is present in the body section of the request.
Example
//Request Head
POST/HTTP/1.1
Host
www.example.com
Content-Type
application/x-www-form-urlencoded
Cookies: username
Pankaj
//Request body
Name=Pankaj & city=Alwar
In case of JSON data
-
- POST / HTTP / 1.1
- Host
- www.example.com
- Content - Type
- application / JSON
- Cookies
- username Pankaj
-
- {“
- Name”: Pankaj,
- “city”: ”Alwar”
- }
Let’s take an example of GET request.
Index.js
- var express = require('express');
- var app = express();
- app.set('view engine', 'pug');
- app.set('views', './views');
- app.get('/demo/:name/:city', function(req, res) {
- res.render('demo', {
- name: req.params.name,
- city: req.params.city,
- state: req.query.state
- });
- });
- app.listen(1400);
demo.pug
- doctype html
- html
- head
- title Hello Pug
- body
- p My Name is# {
- name
- }
- and live in #{
- city
- }
- State is# {
- state
- }
Now save above code and send a get request in browsers as below.
In GET method, we parse the query string easily because the data was present in the URL but in case of POST method, where data is present in request body, we require some extra resources that can perform that task. For this, we will install body parser. Run the command, mentioned below and install all the required packages for body parser and multer. Generally, body-parser is used for parsing the JSON and URL encoded data and multer is used for parsing the multipart/form data.
“npm install --save body-parser multer”
After installing the body parser dependencies, now we create HTML form and send the request to the Server. Let’s create Index.pug file and insert the data, mentioned below into this file.
- <html>
-
- <head>
- <link rel="stylesheet" type="text/css" href="midStyle.css"> </head>
-
- <body>
- <form method="POST" action="/demo">
- <h3>Send Your Request</h3> <span>Name: </span> <input type="text" name="username" />
- </br/> <span>Password: </span> <input type="password" name="password_" /> <br/> <input type="submit" text="Submit" /> </form>
- </body>
-
- </html>
The code, mentioned above generates a form that will contain two textboxes and a submit button.
When we click the submit button, a POST request will send to the Server for demo page. At Server level, we will manage the request and retrieve the data from request body and send some output to the client.
Index.js file
- var express = require('express');
- var app = express();
- var bodyParser = require('body-parser');
- var multer = require('multer');
- var upload = multer();
- app.set('view engine', 'pug');
- app.set('views', './views');
-
- app.use(bodyParser.json());
-
- app.use(bodyParser.urlencoded({
- extended: true
- }));
- app.use('/', express.static(__dirname + '/css'));
-
- app.use(upload.array());
- app.get('/', function(req, res) {
- res.render('index');
- });
- app.post('/demo', function(req, res) {
- if (!req.body) return res.sendStatus(400)
- res.render('demo', {
- UserName: req.body.username,
- pass: req.body.password_
- });
- })
- app.listen(1400);
- var express = require('express');
- var app = express();
- var bodyParser = require('body-parser');
- var multer = require('multer');
- var upload = multer();
- In the starting of the code we implement the“ express”, ”body - parser” and“ multer” modules.
- app.set('view engine', 'pug');
- app.set('views', './views');
- Above both lines define the view engine and the path
- for the templates that will be render to the client.
- app.use(bodyParser.json());
In this line, we define a middleware that will manage that will parse the JSON data from body.
app.use(bodyParser.urlencoded({ extended: true }));
In the line mentioned above, we add another middleware function that will parse the encoded data from the body.
app.use(upload.array());
This line of code is used to parse the multipart data from the form. In the response of the POST request, we return the “demo” template page to the user. Code of the demo.pug page is shown below.
- doctype html
- html
- head
- title Hello Pug
- body
- div(style = "color:blue;font-size:24px")
- p My Name is# {
- UserName
- }
- and Your Password is# {
- pass
- }
Example
Output
In this example, we use HTML code in index.pug file, which is not good for the coding side point of view. We should be using the PUG(JADE) language standard. Hence, you can use the code, mentioned below for “index.pug” file.
Index.pug
- html
- head
- title "hello Pug"
- link(rel = 'stylesheet', href = 'midStyle.css')
- body
- form(action = "/demo"
- method = "POST")
- h3 Enter Your Details
- label(
- for = "username")(style = "color:red") Name: input(name = "username"
- value = "name"
- type = "text")
- br
- label(
- for = "password_") Password: input(name = "password_"
- type = "password")
- br
- button(type = "submit") Send request
Above code will generate the following output. In this code we use a css style sheet in code that contain some style for our page.
When you enter name, password info and press the submit button, you get the same result as you got in previous example.
Send JSON data using AJAX Method
In the previous example, we post the whole form to the Server and at the Server, we fetch the data from the body. Now, we learn how to send JSON data and get the response from the Server.
Index.Pug
- html
- head
- title "hello Pug"
- link(rel = 'stylesheet', href = 'midStyle.css')
- script(src = "jquery-3.1.1.js")
- script(src = "myJquery.js")
- body
- h3 Enter Your Details
- label(
- for = "username")(style = "color:red") Name: input(value = "name")(type = "text")(id = "name")
- br
- label(
- for = "password_") Password: input(type = "password")(id = "password")
- br
- button(type = "submit"
- id = "submit") Send request
- div(id = "data")
MyQuery.js
- $(document).ready(function() {
- $("#submit").click(function() {
- var name = $("#name").val();
- var pass = $("#password").val();
- var data_ = {
- username: name,
- password_: pass
- };
- alert(data_);
- $.ajax({
- type: "POST",
- url: "/demo",
- data: JSON.stringify(data_),
- contentType: "application/JSON",
- dataType: "HTML",
- }).done(function(data) {
- $("#data").html(data);
- }).fail(function(data) {
- alert("Error");
- })
- })
- })
In the code mentioned above, we add a JavaScript file in which we are using AJAX to send a POST request to the Server and displays the result into a div retrieved from server.
Index.js
- var express = require('express');
- var app = express();
- var bodyParser = require('body-parser');
- var multer = require('multer');
- var upload = multer();
- app.set('view engine', 'pug');
- app.set('views', './views');
-
- app.use(bodyParser.json());
-
- app.use(bodyParser.urlencoded({
- extended: true
- }));
- app.use('/', express.static(__dirname + '/css'));
- app.use('/', express.static(__dirname + '/Scripts'));
-
-
- app.get('/', function(req, res) {
- res.render('index');
- });
- app.post('/demo', function(req, res) {
- if (!req.body) return res.sendStatus(400)
- res.render('demo', {
- UserName: req.body.username,
- pass: req.body.password_
- });
- })
- app.listen(1400);
In index.js file, we establish the Server credentials and for “POST” requesy of “/demo”, we rendered the “demo” template.
demo.pug
- doctype html
- html
- head
- title Hello Pug
- body
- div(style = "color:blue;font-size:24px")
- p My Name is# {
- UserName
- }
- and Your Password is# {
- pass
- }
Output
Overall process is that after inserting the name and password value, when we click on “Send request” button a POST type request will send to the Server for “demo” page and at the Server level, we are rendering a demo” template to the user that will return the name and password that we fetched out from the request body.
Conclusion
In this article, we learn how to fetch the data from request and how can we parse JSON and URL encoded data from the request. I hope, you liked this article. Thanks for reading the article.