Building HTTP Servers

Hello All,

Welcome back to NodeJs series. Today we are are going to discuss about Building HTTP Server

HTTP => (Hypertext Transfer Protocol) HTTP is an application-level protocol for content and application delivery. It uses TCP as its transport protocol, and it is the foundation of data communication for the World Wide Web.One of the preferred application deployment mechanisms is to provide an HTTP service on the Internet that answers HTTP client requests.

Creating an HTTP server

 

Save the file with any file name with .js extension.                                                                                                                  for Example  You can then save this script into a file named server.js and start it like this:                                              $ node server.js     Run on terminal

When a client makes a request, the HTTP server emits a request event, passing in HTTP request and HTTP response objects. The HTTP request object allows you to query some of the request properties, and the HTTP response allows you to build an HTTP response that will be sent to the client.

The created server can then be accessed with the URL http://localhost:1337 in the browser.

The Http.ServerRequest Object

When listening for request events, the callback gets an http.ServeerRquest object as the first argument. This object contains some properties you can inspect, including the url , method , and headers properties:

req.url: This property contains the requested URL as a string. It does not contain the
schema, hostname, or port, but it contains everything after that. E.g.

 

Open http://localhost:1337/abc using a browser. Change the path in the URL to see  how it behaves.

req.method: This contains the HTTP method used on the request. It can be, for example, GET , POST , DELETE , or HEAD .

req.headers: This contains an object with a property for every HTTP header on the request. To analyze it, you can   run this server:

 

Here you are using util.inspect() , a utility function that analyzes the properties of any object.

When you get the request event  on a server, you don’t immediately get the body of that request, simply because      it has not arrived yet. But if you want to, you can listen for data events, or even pipe the request body into a WriteStream, such as a file or a TCP connection, because the request object is a ReadStream:

 

The Http.ServerResponce Object

The response object (the second argument for the request event callback function) is used to reply to the client.
Writing a Header

To write a header, use res.writeHead(status, headers) , where headers is an optional argument with an object containing a property for every header you want to send. Consider this example:

 

This example sets two headers, one labeled “Content-Type: text/plain” and another labeled  “Cache-Control: max-age=3600” .   Save with name http_Server.js and Run

$ node http_Server.js

using a command-line HTTP client like curl :   $ curl -i http://localhost:1337

See Output : HTTP/1.1 200 OK
Content-Type: text/plain
Cache-Control: max-age=3600
Connection: keep-alive
Transfer-Encoding: chunked
Hello World!

You can change a header you already set or set a new one by using the following:                                                                            res.setHeader(name, value);

NOTE  =>  This works only if you haven’t already sent a piece of the body by using res.write() or res.end() . This also fails to work if you have already used res.writeHead() on that response object, because the headers also will have already been sent.

Removing a Header 

You can remove a header you have already set by calling res.removeHeader and providing the header name:                                     res.removeHeader(‘Cache-Control’);                                                                                                        Again, this works only if the headers for that response haven’t already been sent.

HTTP CHUNKED RESPONSES 

One of the great features of Node is the ability to consume and produce streams easily from different sources. Because HTTP is a fi rst-class protocol in Node, the HTTP responses are no different.                                                  HTTP chunked encoding allows a server to keep sending data to the client without ever sending the body size. Unless you specify a Content-Length header, the Node HTTP server sends the following                                                        Transfer-Encoding: chunked

According to the HTTP specification, this header makes the client accept several chunks of data as the response body, sending a final chunk with a length of 0 before the client can terminate the response. This can be useful for streaming text, audio, or video data into the HTTP client.

SHUTTING DOWN THE SERVER

You can stop an HTTP server from accepting new connections by unbinding it from the port like this: server.close();   If you want it to start listening again, you have to repeat the following server.listen(port[, hostname]);

A basic example of HTTP server.
write following code in http_server.js file:
 

go  your http_server.js location run this command:

$ node http_server.js
you should see this result:
                       > Start HTTP on port 8000
now you need to test your server, you need to open your internet browser and navigate to this url:
                              http://localhost:8000
if your machine running Linux server you can test it like this:
curl -i http://localhost:8000
you should see following result:
ok
in your console, that running the app, you will see this results:
> Request received: HTTP GET /
> Client IP: ::ffff:127.0.0.1

SUMMARY

The Node http allows you to create an HTTP server and make it listen on a specific port and host. You can then listen to new request events where, for each request, a callback function gets the corresponding ServerRequest and ServerResponse objects.

We can observe some properties from the request object like the request URL and the headers. The ServerRequest object is also a ReadStream, meaning that you can, among other things, listen for data events containing streamed body data parts, and even pipe that data into another stream.

With the ServerResponse object you can reply to the client by setting the HTTP response status and sending the response headers. You can also write to the response body or even pipe any ReadStream into it. In cases where you don’t know the content length or you want a continuous response stream, you can use the HTTP chunked response protocol to stream the content body, where the server sends several chunks of the response body.