Search This Blog


Managing HTTP request using Node JS

In this demo, we are going to look at how we can process a "POST" request that is going to come in with some form data within our Node application. And to do that, we are going to be using the help of the "connect" module and also the "body-parser" module.

Step 1: Run "npm init"

Step 2 : Insert all required parameter in 'npm init' and create the start page 'index.js'.

Step 3: In package.json , add the dependencies as below

"dependencies": {
"Connect": "*"

Step 4: in 'index.js', write the following code

var http=require('http');
var connect=require('connect');
var bodyParser=require('body-parser');

//bodyParser.urlencoded is going to make it easy for me to work with http form data by populating the body object of the http request that comes in, so I can //easily access that data.

var app=connect()
//Handler Method
var parsedInfo={};
access the userFirstName and the userLastName properties of the body

res.end("User Infor Parsed from: " +parsedInfo.firstName+" " + parsedInfo.lastName)

 console.log("listening from 3456"); 

Step 5: Create a Html page with the following content


 <title>User Infor From Page</title>

  <h2>Enter Detail and Submit</h2>
  <form action="http://localhost:3456" method="POST">
 First Name:<input Type="text" name="userFirstName"/>
 Last Name:<input Type="text" name="userLastName"/>
 <input type="submit" name="submit"/>

 User Info From Page

Enter Detail and Submit


 First Name:
 Last Name:


Step 6: run 'node index.js'

Step 7: Open the HTML page in browser, insert First & Last name and  submit the page.

Step 8:You will get the response in browser , as per the response object.

No comments: