Node.js - Query String And API - Day Twelve

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
  1. //Request Head  
  2. POST / HTTP / 1.1  
  3. Host  
  4. www.example.com  
  5. Content - Type  
  6. application / JSON  
  7. Cookies  
  8. username Pankaj  
  9. //Request body  
  10. {“  
  11.     Name”: Pankaj,  
  12.     “city”: ”Alwar”  
  13. }  
Let’s take an example of GET request.

Index.js

  1. var express = require('express');  
  2. var app = express();  
  3. app.set('view engine''pug');  
  4. app.set('views''./views');  
  5. app.get('/demo/:name/:city'function(req, res) {  
  6.     res.render('demo', {  
  7.         name: req.params.name,  
  8.         city: req.params.city,  
  9.         state: req.query.state  
  10.     });  
  11. });  
  12. app.listen(1400);  
demo.pug
  1. doctype html  
  2. html  
  3. head  
  4. title Hello Pug  
  5. body  
  6. p My Name is# {  
  7.     name  
  8. }  
  9. and live in #{  
  10.     city  
  11. }  
  12. State is# {  
  13.     state  
  14. }  
Now save above code and send a get request in browsers as below.

demo.pug

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”

demo.pug

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.
  1. <html>  
  2.   
  3. <head>  
  4.     <link rel="stylesheet" type="text/css" href="midStyle.css"> </head>  
  5.   
  6. <body>  
  7.     <form method="POST" action="/demo">  
  8.         <h3>Send Your Request</h3> <span>Name: </span> <input type="text" name="username" />  
  9.         </br/> <span>Password: </span> <input type="password" name="password_" /> <br/> <input type="submit" text="Submit" /> </form>  
  10. </body>  
  11.   
  12. </html>  
The code, mentioned above generates a form that will contain two textboxes and a submit button.

demo.pug

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
  1. var express = require('express');  
  2. var app = express();  
  3. var bodyParser = require('body-parser');  
  4. var multer = require('multer');  
  5. var upload = multer();  
  6. app.set('view engine''pug');  
  7. app.set('views''./views');  
  8. // for parsing application/json  
  9. app.use(bodyParser.json());  
  10. // for parsing application/x-www-form-urlencoded  
  11. app.use(bodyParser.urlencoded({  
  12.     extended: true  
  13. }));  
  14. app.use('/', express.static(__dirname + '/css'));  
  15. // for parsing multipart/form-data  
  16. app.use(upload.array());  
  17. app.get('/'function(req, res) {  
  18.     res.render('index');  
  19. });  
  20. app.post('/demo'function(req, res) {  
  21.     if (!req.body) return res.sendStatus(400)  
  22.     res.render('demo', {  
  23.         UserName: req.body.username,  
  24.         pass: req.body.password_  
  25.     });  
  26. })  
  27. app.listen(1400);  
  28. var express = require('express');  
  29. var app = express();  
  30. var bodyParser = require('body-parser');  
  31. var multer = require('multer');  
  32. var upload = multer();  
  33. In the starting of the code we implement the“ express”, ”body - parser” and“ multer” modules.  
  34. app.set('view engine''pug');  
  35. app.set('views''./views');  
  36. Above both lines define the view engine and the path  
  37. for the templates that will be render to the client.  
  38. 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.
  1. doctype html  
  2. html  
  3. head  
  4. title Hello Pug  
  5. body  
  6. div(style = "color:blue;font-size:24px")  
  7. p My Name is# {  
  8.     UserName  
  9. }  
  10. and Your Password is# {  
  11.     pass  
  12. }  
Example

demo.pug

Output

demo.pug

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
  1. html  
  2. head  
  3. title "hello Pug"  
  4. link(rel = 'stylesheet', href = 'midStyle.css')  
  5. body  
  6. form(action = "/demo"  
  7.     method = "POST")  
  8. h3 Enter Your Details  
  9. label(  
  10.     for = "username")(style = "color:red") Name: input(name = "username"  
  11.     value = "name"  
  12.     type = "text")  
  13. br  
  14. label(  
  15.     for = "password_") Password: input(name = "password_"  
  16.     type = "password")  
  17. br  
  18. 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.

demo.pug

When you enter name, password info and press the submit button, you get the same result as you got in previous example.

demo.pug

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


demo.pug
  1. html  
  2. head  
  3. title "hello Pug"  
  4. link(rel = 'stylesheet', href = 'midStyle.css')  
  5. script(src = "jquery-3.1.1.js")  
  6. script(src = "myJquery.js")  
  7. body  
  8. h3 Enter Your Details  
  9. label(  
  10.     for = "username")(style = "color:red") Name: input(value = "name")(type = "text")(id = "name")  
  11. br  
  12. label(  
  13.     for = "password_") Password: input(type = "password")(id = "password")  
  14. br  
  15. button(type = "submit"  
  16.     id = "submit") Send request  
  17. div(id = "data")  
demo.pug

MyQuery.js
  1. $(document).ready(function() {  
  2.     $("#submit").click(function() {  
  3.         var name = $("#name").val();  
  4.         var pass = $("#password").val();  
  5.         var data_ = {  
  6.             username: name,  
  7.             password_: pass  
  8.         };  
  9.         alert(data_);  
  10.         $.ajax({  
  11.             type: "POST",  
  12.             url: "/demo",  
  13.             data: JSON.stringify(data_),  
  14.             contentType: "application/JSON",  
  15.             dataType: "HTML",  
  16.         }).done(function(data) {  
  17.             $("#data").html(data);  
  18.         }).fail(function(data) {  
  19.             alert("Error");  
  20.         })  
  21.     })  
  22. })  
demo.pug

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
  1. var express = require('express');  
  2. var app = express();  
  3. var bodyParser = require('body-parser');  
  4. var multer = require('multer');  
  5. var upload = multer();  
  6. app.set('view engine''pug');  
  7. app.set('views''./views');  
  8. // for parsing application/json  
  9. app.use(bodyParser.json());  
  10. // for parsing application/x-www-form-urlencoded  
  11. app.use(bodyParser.urlencoded({  
  12.     extended: true  
  13. }));  
  14. app.use('/', express.static(__dirname + '/css'));  
  15. app.use('/', express.static(__dirname + '/Scripts'));  
  16. // for parsing multipart/form-data  
  17. //app.use(upload.array());   
  18. app.get('/'function(req, res) {  
  19.     res.render('index');  
  20. });  
  21. app.post('/demo'function(req, res) {  
  22.     if (!req.body) return res.sendStatus(400)  
  23.     res.render('demo', {  
  24.         UserName: req.body.username,  
  25.         pass: req.body.password_  
  26.     });  
  27. })  
  28. 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
  1. doctype html  
  2. html  
  3. head  
  4. title Hello Pug  
  5. body  
  6. div(style = "color:blue;font-size:24px")  
  7. p My Name is# {  
  8.     UserName  
  9. }  
  10. and Your Password is# {  
  11.     pass  
  12. }  
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.

demo.pug

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.


Similar Articles