Building HTTP Server Using HTTP API - 1
Overview
Whenever you do an action in a browser, you are sending a request to some other computer on the internet, which response by sending you the webpage. That device you're communicating with over the internet is a web server. A web server takes HTTP requests from clients such as your browser and responds with an HTTP response such as an HTML page or JSON from an API. Node.js enables developers to use JavaScript to create back-end code, even though it was previously used to produce front-end code in browsers. The HTTP API makes it simple to start up an HTTP server in Node.js.
Introduction to HTTP Servers
HTTP stands for Hypertext Transfer Protocol, and it is an application layer protocol that is predominantly used with the WWW (World Wide Web) in the client-server architecture, where a web browser is a client interacting with the webserver that is hosting the website.
An HTTP server is a computer program or a software component of another program that acts as a server in a client-server model by implementing the server portion of the HTTP and/or HTTPS network protocols.
An HTTP server waits for incoming client requests and responds to each one by returning desired information, including the delivery of the requested web page, or by returning an HTTP error message.
To support program-to-program communications, an HTTP server may also contain bindings to manage protocol extensions to HTTP or messages of other protocols enveloped in HTTP messages.
The HTTP or web server processes HTTP requests, which is a network protocol used to communicate data on the World Wide Web (WWW). An HTTP server's primary duty is to store, process, and distribute web pages to clients. Pages are often given as HTML documents that may include graphics, style sheets, and scripts in addition to text content. You explain how a page should look, what fonts to use, what color the text should be, where paragraph marks should appear, and many other features of the content using HTML.
Creating a Basic HTTP Server
Now let’s start by building a server that returns plain text to the user. This will cover the fundamental concepts required to build up a server, which will lay the groundwork for returning more complicated data types.
You need to have Node.js installed in your system. You can easily install Node.js with the help of the installer provided on the official Node.js website.
Next, create a directory for this project and name it node-http-server. You can use the following command for this task:
Then switch to that folder :
Now create a file server.js in which you will be writing the code.
In the file write the code as we discuss below.
First load the http module which is a core Node.js module and hence doesn't require installation. Add the following line to server.js :
The http module has the required functions for creating the server. Now create two constants two stores of the value of the hostname and the port:
Web servers, as previously stated, accept requests from browsers and other clients. We can communicate with a web server by entering a domain name, which a DNS server converts to an IP address. An IP address is a unique sequence of characters that identifies a computer on a network such as the internet.
The localhost is a private address used by computers to refer to themselves. It is equivalent to the internal IP address 127.0.0.1 and is only accessible to the local computer and not to any local networks connected or to the internet.
The port is a number that servers use to connect to a specific process on our IP address as an endpoint or door. In this example, we will run our web server on port 8000. Ports 8080 and 8000 are commonly used as default ports in development, and most developers will use them for HTTP servers rather than other ports. The server is bound to the host and port, and hence you will be able to access it on http://localhost:8000.
Create a function requestListener to handle the incoming requests. This function requires two parameters: a request object and a response object. The request object stores all of the data from the incoming HTTP request. The response object is responsible for returning HTTP responses to the server, and it contains all the details about the response.
The function will return Welcome user!! as a response to the client.
In Node.js, all request listener functions take two arguments: req and res . The user's HTTP request is stored in the Request object (req) which is the first argument. We generate the HTTP response that we return to the user by modifying the Response object (res) in the second argument.
The first line of code, res.writeHead(200), specifies the HTTP status code of the response. HTTP status codes represent how well a server handled an HTTP request. The status code 200 corresponds to OK in this instance. The function's next line, res.end("Welcome user!!"), returns the HTTP response to the client who requested it. This function returns any data to be sent from the server. It is returning text data in this case.
Now add the following code in the file to create the server :
First, the server object is created using the createServer() function. The server object accepts all the requests and passes them to the requestListener() function. The server is then attached to the port and host using the server.listen to () function. The listen to () function takes the port, host and the callback function as arguments. The callback function is called when the server begins to listen.
Now your final code in the file should be :
Example :
Now run the code using the below command :
In the console, we will see this output :
Now you can open http://localhost:8000/ in a browser to see the output.
You have now set up your server. We used a browser to send a GET request to the server at http://localhost:8000. Our Node.js server was monitoring connections on this address. The request was passed to the requestListener() function by the server. With the status code 200, the method returned text data. After that, the server returned the response to the browser, which displayed the message.
You can use CTRL+C to shut down the server.
Returning Different Types of Content
The format of the response we receive from a web server can vary. Text formats like JSON, CSV, XML, and HTML can be easily returned. Other than these, non-text data such as PDFs, compressed files, audio, and video can be returned by web servers. JSON, CSV, and HTML are all text-based data types. They are prominent web content delivery types. Many server-side development languages and tools enable returning these various data kinds.
In Node.js, you need to do the following two things :
- Set the suitable value for the Content-Type header in your HTTP responses.
- Check that res.end() receives the data in the correct format.
You will be making changes mostly in the requestListener to return different content types.
Serving JSON
JavaScript Object Notation, or JSON for short, is a text-based data transmission standard. It is derived from JavaScript objects, as the name implies, but it is language-independent, which means it may be used by any programming language that can parse its syntax.
APIs frequently utilize JSON to accept and return data. Its popularity comes from its smaller data transfer size over previous data interchange formats, such as XML, as well as the availability of technology that allows applications to parse it with minimal effort.
Now to serve JSON, make the following changes to the requestListener:
The method res.setHeader() inserts an HTTP header to the response. HTTP headers are used to include additional information to request or respond. The res.setHeader() requires two parameters: the name and value of the header.
The Content-Type header is used to specify the data format or the media type, that is transmitted with the request or response. Our Content-Type in this example is application/json.
Now your code will become :
On running it you will receive the following output in your browser :
Serving CSV
The Comma Separated Values (CSV) file format is a text standard used to provide tabular data. Generally, in a CSV file, a newline separates each row, and a comma separates each item in the row.
In the case of a CSV file, the browser downloads the file automatically.
Make the following changes to the requestListener:
The Content-Type shows that a CSV file is being sent this time, as the value is text/csv. Content-Disposition is the second header that is added. This header instructs the browser on how to display the data, whether in the browser or a separate file.
Even if the Content-Disposition header is not set most browsers download the file in the case of CSV. The header should be included as it allows us to set the name of the file that will be downloaded at the user's end. In this case, the name will be users.csv.
Now your complete code must be like this :
Example :
On running the code your browser will download the file users.csv if you visit the http://localhost:8000.
The file will have the following contents when opened using a text editor :
- id, name,email
- 1, John Doe,john@gmail.com
Serving HTML
When we want users to communicate with our server via a web browser, we typically utilize HTML or HyperText Markup Language. Web browsers are designed to show HTML text as well as any CSS styles we add to our websites. CSS is another front-end web technology that allows us to modify the look of our websites.
Make the following changes to the requestListener:
First, we include the HTTP status code. Then, using a string argument containing valid HTML, we call the response.end() function. When we use the browser to connect to our server, we will see an HTML page with one paragraph tag that says This is an HTML page.
Now your complete code must be like this :
Example :
On running the code your browser will display the following on http://localhost:8000.
This is an HTML page.
Serving HTML Page from a File
we can also serve an html page from a file as the response. We utilize the fs module to load the HTML file and use its data while generating our HTTP response to deliver HTML files.
Consider the case of a sample HTML page hello.html that needs to be displayed.
We must now read the file before we can import it, which is accomplished with the help of the fs module.
A function called readFile() is available in the fs module and is typically used to load HTML files. We import the promised variation of the call to stay current with contemporary JavaScript conventions. Additionally, in many situations, it is superior to callbacks.
After updating the running js file with this information, we must return the page using it.
Example :
Here, the file is loaded using the fs.readFile() method. __dirname and /samplePage.html are its two inputs. The absolute path, where Node.js code is now being executed, is represented here by the variable __dirname. To load the HTML file we want to serve, we can then add /samplePage.html to this route.
The data will be returned once the fs.readFile() promise has been successfully resolved. Then, to handle this follow-up situation, we use the then() method. The HTML file's real data is located in the contents parameter.
Handle Routes by HTTP Request Object
The majority of websites and APIs that we visit or use typically have many url endpoints so that we can access the various resources that are offered on the same platform. An inventory management scenario, such as one that might be employed in a warehouse, is a typical example.
To handle requests whose URL contains other destinations, we have not yet implemented any extra routing logic inside the requestListener() function.
In the following example, we will be constructing a new server for a simple inventory system, which can return 2 different sorts of data.
Server’s address endpoint at:
- /manufacturers will provide a list of manufacturers' information in JSON.
- /items will provide a list of items with their respective quantities in JSON.
Let's take two variables:
- The items variable is a string containing JSON for a collection of item objects.
- The manufacturers is a string containing the JSON for an array of manufacturer objects.
We will receive that in response now that we have included the data in the responses. To do that, we must edit the requestListener() function. However, before we can do that, we must make sure that every server answer contains the appropriate Content-Type header, in this case, a JSON header. The correct JSON must then be returned based on the user's chosen URL route. We must access the property 'url' in the request object to obtain a URL path. We may build the following switch statement on the request's URL based on this differentiator :
Example :
Similar to what we did earlier when a call is successful, we set the response code to 200 and return the JSON. An error for the same can be denoted by the Default case. Here, the meaning of 404, which means resource not found, is clearer.
Conclusion
- A HTTP server is a computer program or a software component of another program that acts as a server in a client-server.
- A HTTP server's primary duty is to store, process, and distribute web pages to clients.
- A HTTP server's primary duty is to store, process, and distribute web pages to clients.
- The localhost is a private address used by computers to refer to themselves.
- The port is a number that servers use to connect to a specific process on our IP address as an endpoint or door.
- Response we receive from a web server can be text-based like JSON, CSV, HTML, or non-text data such as PDFs, compressed files, and audio.
- We can also serve an html page from a file as the response while utilizing the fs module.
- A function called readFile() is available in the fs module and is typically used to load HTML files.