Node - Js Modules and HTML Form Handling
Node - Js Modules and HTML Form Handling
Js modules
and html form handling
What is a Module
The module is a small self-contained piece
of code. You can include module using the
“require” statement.
A module encapsulates related code into a
single unit of code. When creating a module,
this can be interpreted as moving all related
functions into a file.
There are two types of modules:
1. User defined
2. System Default
You can use file and folder both as the
module. You can load the module from the
“node_modules” folder.
Exporting a Module
Here, we have created a module which is module1.js.
You can also use require(‘./module1’), means no need
to write an extension, it will check first for module1.js
file and if not found, will check for folder and if not
found will generate the error.
main.js
misc_main.js
Example-2
Create a folder testnodejs
Create three files module1.js,module2.js and index.js
module1.js
index.js
module2.js
Output is
Another module to export
Example-3
module3.js
index.js
Output
Creating web application using
Node.js
Creating a web application (to be more
precise, a web server) in Node.js, you write a
single JavaScript function for your entire
application. This function listens to a web
browser’s requests, or the requests from a
mobile application consuming your API, or any
other client talking to your server. When a
request comes in, this function will look at the
request and determine how to respond. If you
visit the homepage in a web browser, for
example, this function could determine that
you want the homepage and it will send back
some HTML. If you send a message to an API
endpoint, this function could determine what
you want and respond with JSON.
Creating an HTTP Server With a Form in
Node.js
Server1.js
form.html
We’ll also need to create a form.html file
which will contain the HTML code to render
the form as shown below:
Anatomy of an HTTP
Transaction
Any node web server application will at some point have to
create a web server object. This is done by using
createServer. The function that's passed in to createServer
is called once for every HTTP request that's made against
that server, so it's called the request handler.
When an HTTP request hits the server, node calls the
request handler function with a few handy objects for
dealing with the transaction, request and response.
In order to actually serve requests, the listen method needs
to be called on the serverobject. In most cases, all you'll
need to pass to listen is the port number you want the
server to listen on.
Method, URL and Headers
◦ The method here will always be a normal HTTP method/verb. The url is
the full URL without the server, protocol or port. For a typical URL, this
means everything after and including the third forward slash. All headers
are represented in lower-case only, regardless of how the client actually
sent them. This simplifies the task of parsing headers for whatever
purpose.
Request Body
When receiving a POST or PUT request, the
request body might be important to your
application. Getting at the body data is a little
more involved than accessing request headers.
The request object that's passed in to a handler
implements the ReadableStream interface. This
stream can be listened to or piped elsewhere just
like any other stream. We can grab the data right
out of the stream by listening to the
stream's 'data' and 'end‘ events.
The chunk emitted in each 'data' event is
a Buffer. If you know it's going to be string data,
the best thing to do is collect the data in an
array, then at the 'end', concatenate and
stringify it.
Setting Response Headers: you
can explicitly write the headers to the response
stream. To do this, there's a method
called writeHead, which writes the status code and
the headers to the stream. Once you've set the
headers, you're ready to start sending response data.
Sending Response Body: Since
the response object is a WritableStream, writing a
response body out to the client is just a matter of
using the usual stream methods.
The end function on streams can also take in some
optional data to send as the last bit of data on the
stream
It's important to set the status
and headers before you start
writing chunks of data to the
body, since headers come before
the body in HTTP responses.
About Errors
An error in the request stream presents itself
by emitting an 'error' event on the stream. If
you don't have a listener for that event,
the error will be thrown, which could
crash your Node.js program. You should
therefore add an 'error' listener on your
request streams, even if you just log it and
continue on your way.
The response stream can also
emit 'error' events.
The HTTP status code on a response will
always be 200.
response.statusCode = 404; // Tell the client that the
resource wasn't found.
fs is a built-in module in the platform for accessing file
system. Using fs, we can perform CRUD operations over
files and directories. It contains both synchronous and
asynchronous APIs for talking to the file system. Use of
asynchronous API is preferred as it will not block the
event loop till the operation is completed.
In the above code we’ve created a HTTP server. readFile()
is used to read the form.html file. The form.html file
contains the HTML code to build the fields of a form which
is meant to be displayed to the user. If we click on the
“Submit” button, it’ll do a get/post request with the
submitted form information to the same URL.
Here we first grab the requested url parts and then check
the pathname for '/' and the page with form will be sent
to client side. Now user can see the page with the form.
When user fills up and submits the form then server will
get the request 'http://localhost:8080/getData' and the
grabbed data will be sent back to client side with a
confirmation message.
We know Node.js is a event driven IO platform. So
here we implemented the data event handler, the
body variable taking all the data and finally the
qs.parse() method pasres the data into different
parts as the form fields. To use the qs.parse() we
need to require the module named 'querystring'.
Finally the data found from the POST request is
sent back to the client as a confirmation.
We used the module 'querystring' to parse the
data into the POST. In the POST processing code
see the req.on is waiting for the data event and
when the data event happens we grab the data
and finally at the data event 'end' we parse the
data and send back to the client side.
We can test the system for GET and POST by
changing the form method to get and post.
So this form will be sent to client side on client
request. After filling up and successfully submission
the form, the form data is grabbed and processed.
The form will submitted to the getData function.
Finally this will process the data and send a message.
Then, we’re starting the server at port 5000. After
starting the server, if we go to localhost:5000 we
should see the HTML form displayed as shown below.