Hello friends, in the post we are going learn how to work with a HTML form in express js, that means we will learn how can we send data from a HTML form to express js server and then how can we handle the requested data in express js scripting.
In this post we will cover following points,
- Required Modules
- Basic Express Routing
- req ( request ) object
- res ( response ) object
- How to send a html file to client
- How to send the form inputs to express server
- How to handle form inputs at express server
- Complete example of working with form in express
Note :
Before doing this example make sure that you have installed NodeJS on your system.
Required Modules :
For this example we need following npm modules,
- express module: to create server and to handle the request and response from client ( browser ) and server respectively.
- body-parser: to parse the request body from request object or simply to get the form data as request body.
To install these to module use following commands on your command prompt,
> npm install express ( to install express )> npm install body-parser ( to install body-parser )
Basic Express Routing :
To determine the client request to a particular endpoint ( i.e URI or path ) and a specific HTTP request method ( i.e GET, POST, etc ), we need the concept of routing.
Following is the syntax to define a route in express,
app.METHOD(PATH, HANDLER)
Where,
- app is the instance of express
- METHOD is an HTTP request method such as GET, POST, PUT and DELETE
- PATH is a path on the server
- HANDLER is the function executed when the route is matched to the requested path
For Example,
Let's take an example that http://localhost:3000/getHelloWorld is the GET request from client, then following is the definition of route,
aap.get('/getHelloWorld', function(req, res){// Logic to handle the request});
req ( request ) object :
The req ( request ) object represents the HTTP request from client to server. It has following properties and methods,
- baseUrl
- body
- cookies
- freshhostname
- ip and
- get()
- param() and so on
res ( response ) object :
The res ( response ) object representd the HTTP response from server to client. It has following properties and methods,
- app
- headersSent
- locals
- append()
- send()
- get()
- json() and so on
Following figure shows how req and res object interact to client/browser and server,
How to send a HTML file from client to server :
The above res ( response) object contains a method i.e res.sendFile() by using which we can send a HTML file from server to client in express.
For example we need a index.html from server, then following is the code to give the response as index.html,
res.sendFile
(__dirname + '/index.html');
Where index.html will be available in your project directory. This file you need to create and you need to save in project directory.
How to send the form inputs to express server :
In the form action attribute we need to mention the request path and when we will submit the form using submit button the form input data will directly send to the route for the requested path.
For example the host is localhost, port is 3000 and the route path is getFormData where we will handle the input data then the request path will be http://localhost:3000/getFormData. We need to mention this path in the form action attribute as follows,
<form method = "post" action = "http://localhost:3000/getFormData"></form>
How to handle form inputs at express server :
It is easy to handle the form input data in express. By default body object present in side the req ( request ) object by using which we can able handle the form inputs values.
By default the the body object is undefined and to to make this defined in req object we need to use body-parser module.
Following line shows the way to handle the form input data as present in side the body object,
var form_data = req.body.ename;
Where ename is the name of the form input element which represent employee name ( for example ).
Complete example of working with form in express :
Following are the complete code of this example
form.html
<!DOCTYPE html>
<html>
<head>
<title> How to work with Form in Express </title>
</head>
<body>
<form method = "post" action = "http://localhost:3000/display-form-data">
Enter Your Name : <input type = "text" name = "ename">
<br>
<br>
<input type = "submit" name = "Submit">
</form>
</body>
</html>
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/form', function(req, res){
console.log(req);
res.sendFile(__dirname + '/form.html');
});
app.post('/display-form-data', function(req, res){
var form_data = req.body.ename;
console.log(form_data);
res.send("You have entered : " + form_data);
});
app.listen(3000, function(){
console.log("Server is at : 3000");
});
Note :
- To run this application go to command promot -> go to the project folder by using the command cd -> type node app.js to run the application.
- After application running success full you will see a message on command prompt by saying Server is at : 3000.
- Try to load the URL i.e http://localhost:3000/form then you will see the form with the input element and try to experiment with the form.
- Make your project directory as follows,
Project Name/App Name
|
|
|--------------> app.js
|
|--------------> form.html
We will post more articles regarding this in future days. If you need any clarity or any help please give a comment below, we will clarify with proper example and concepts, Thanks :) .
Err > var form_data = req.body.nm;
ReplyDeleteCorr > var form_data = req.body.ename;
Thanks for detecting the error :)
ReplyDelete