Hello readers, In this tutorial, we are going learn how can we create HTTP Server with Forms in Node.Js.

Introduction:

An HTML Form is a group of one or more fields/widgets on a web page that can be used to collect information from users for submission to a server. Forms are a flexible mechanism for collecting user input because there are suitable form inputs available for entering many different types of data—text boxes, checkboxes, radio buttons, date pickers, etc. Forms are also a relatively secure way of sharing data with the server, as they allow us to send data to POST requests with cross-site request forgery protection.
In this tutorial, we’re going to show you how the above operations may be performed in Node Js.

Creating HTTP Server with Forms in Node.Js:

Let’s start creating HTTP Server that will show HTML form to the User. Create a Js file called FormDemo.js and write the following code.

var http = require('http');
var fs = require('fs');
var server = http.createServer(function (req, res) {
displayForm(res);
});

function displayForm(res) {
fs.readFile('Employee.html', function (err, data) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': data.length
});
res.write(data);
res.end();
});
}

server.listen(3000);
console.log("server listening on 3000");

Create Employee.html:

Create Employee.html file that will contain HTML code.

<html>
<head>
<title>
Forms in Node.js
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" />
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">

<div class="form-group">
<label for="txtName">Name</label>
<input type="text" class="form-control" id="txtName" placeholder="Enter Name">
 
</div>
<div class="form-group">
<label for="txtAddress">Address</label>
<textarea class="form-control" id="txtAddress" rows="3"></textarea>
</div>
<div class="form-group">
<label for="ddlGender">Gender</label>
<select class="form-control" id="ddlGender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
 
 
 
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" class="form-check-input">
I Agree
</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>

</form>
</body>
</html>

Now Open Node Js command Prompt and navigate to your project Location. Now run the following command:

Node FormDemo.js

Forms in Node.js

Now type the following URL in browser http://localhost:3000/.

Output:

Forms in Node.js

View More:

Conclusion:

I hope this session is helpful for you. I would appreciate your feedback and comments.

Thank You,

Leave a Comment