2. Topics
5.1 Creating Web Server
5.2 Handling HTTP requests
5.3 Sending Requests
5.4 HTTP Streaming
3. Introduction
Web Application needs Web Server.
Communication between Client & Server using HTTP.
IIS web server for ASP.NET web application.
Apache web server for PHP and Java web application.
Create Node.Js web server for Node.js application.
4. Creating Node.Js web server
Node.js makes create a simple web server that processes
incoming requests asynchronously.
Following example is a simple Nodejs web server example
var http = require('http'); // http Node.js core module
var server = http.createServer(function (req, res) {
//handle request
}); server.listen(8080); //listen for any incoming requests
console.log('Node.js web server at port 8080 is running..')
5. Creating Node.Js web server
In the above example,
http core module is imported using require() function.
As http module is a core module of Node.js, no need to install it
using NPM.
Next step is call createServer() method of http
In that specify callback function with request and response
parameter.
Finally, call listen() method of server object.
Which start listening to incoming requests on port 8080.
Can specify any unused port here.
6. createServer()
const http = require('http');
const server = http.createServer((request, response) => {
// Task to be done!
});
OR
const http = require('http');
const server = http.createServer();
server.on('request', (request, response) => {
// Task to be done
});
7. CreateServer() Explanation
The function that's passed in to createServer is called once
for every HTTP request.
It works as a request handler.
The server object returned by createServer is an EventEmitter.
HTTP request hits the server, node calls the request handler
function for dealing with the transaction,request and response
8. Simple Hello World Example
var http = require('http');
//create a server object:
var server=http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
});server.listen(8080); //the server object listens on port
8080
9. HTTP Request and Response
The http.createServer() method
includes request and response parameters
The request object can be used to get information about
the current HTTP request e.g.,methods, url, request header,
and data.
The response object can be used to send a response for a
current HTTP request.
10. Handling http request
The first thing while handling request is to check method
and URL, so that appropriate actions can be taken.
Node.js makes this relatively painless by putting handy
properties onto the request object as follows
const { method, url ,header} = request;
Parameter:
method here will GET/POST/PUT normal HTTP
method/verb.
url is the full URL without the server, protocol or port.
11. Request Body
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// body has the entire request body, stored in it as
a string
});
12. Request Body explanation
request object passed in to a handler implements
the ReadableStream interface.
This stream can be listened or piped.
Data can be read out of the stream by listening to the
stream's 'data' and 'end' events.
The chunk emitted in each 'data' event is a Buffer.
Most probably data going to be string data, the best is
to collect the data in an array,
At the 'end', concatenate and stringify it.
13. Error handling while http request
request.on('error', (err) => {
// This prints the error message and stack trace to `stderr`.
console.error(err.stack);
});
The request object is a ReadableStream, which is
an EventEmitter
An error in the request stream presents itself by emitting
an 'error' event.
If event listener is not handle in program then the error will
be thrown.
14. Overall Program of HTTP request
const http = require('http');
http.createServer((request, response) =>
{
const { headers, method, url } = request;
let body = []; request.on('error', (err) =>
{
console.error(err);
}).on('data', (chunk) => {
body.push(chunk); }).on('end', () => {
body = Buffer.concat(body).toString();
});
}).listen(8080);
15. HTTP Response
response object is an instance of ServerResponse which is
a WritableStream.
It contains many methods for sending data back to the
client.
HTTP Status code
HTTP status code on a response always be 200.
Not every HTTP response warrants this such as
response.statusCode = 404; // Tell the client that the resource
wasn't found.
16. Setting Response Headers
Headers are set through a convenient method
called setHeader()
response.setHeader('Content-Type', ‘text/html');
Explicitly Sending Header Data with method
called writeHead() which writes the status code and the
headers to the stream.
response.writeHead(200, { 'Content-Type': ‘text/html’});
17. Sending Response Body
response object is a WritableStream writing a response
body out to the client.
response.write() method is used to write streams.
response.write('<html>');
response.write('<body>');
response.write('<h1>Hello, World!</h1>');
response.write('</body>');
response.write('</html>');
response.end()
OR
response.end('<html><body><h1>Hello,
World!</h1></body></html>');
18. Error handling while http response
response.on('error', (err) => {
// This prints the error message and stack trace to `stderr`.
console.error(err.stack);
});
The response object is a WritableStream, which is
an EventEmitter.
An error in the response stream presents itself by emitting
an 'error' event.
If event listener is not handle in program then the error will
be thrown.