This article has been adapted from lesson 4 of Get Programming with Node.js and covers:.
Share This Article
Generating a basic web server using Node.js and npm. Writing code that processes requests from a browser and sends back a response. Running a web server in your browser. You can take 35% off Get Programming with Node.js by entering snwexler into the discount code box at checkout at manning.com.
You’re on your way to building your first web application. Before you deliver a complete application, the cooking community would like to see a simple site with the flexibility to improve and add features in the future. How long do you think it will take you to build a prototype?
With Node.js, you can use the http module to get a web server with sufficient functionality built within hours. Understanding web servers. Web servers are the foundation of most Node.js web applications.
Handling GET Requests in Node.js
- They allow you to load images and HTML web pages to users of your app. Before you get started, I’ll discuss some important web server concepts. After all, the final product will look and feel a lot better if you have clear expectations of the result. WEB SERVERS AND HTTP.
- A web server is software designed to respond to requests over the internet by loading or processing data. Think of a web server like a bank teller, whose job is to process your request to deposit, withdraw, or view money in your account.
- Just as the bank teller follows a protocol to ensure that they process your request correctly, web servers follow Hypertext Transfer Protocol (HTTP), a standardized system globally observed for the viewing of web pages and sending of data over the internet.
Initializing a Node.js Application
One way that a client (your computer) and server communicate is through HTTP verbs. These verbs indicate what type of request is being made, such as whether the user is trying to load a new web page or updating information in their profile page.
The context of a user’s interaction with an application is an important part of the request-response cycle. Here are the two most widely used HTTP methods you’ll encounter:.
—This method requests information from a server.
Typically, a server responds with content that you can view back on your browser (such as by clicking a link to see the home page of a site).
—This method sends information to the server. A server may respond with an HTML page or redirect you to another page in the application after processing your data (such as filling out and submitting a sign-up form).
I discuss a couple more methods in the book in lesson 18. Most web applications have made changes to adopt HTTP Secure (HTTPS), in which transmission of data is encrypted.
When your application is live on the internet, you’ll want to create a public key certificate signed by a trusted issuer of digital certificates. This key resides on your server and allows for encrypted communication with your client.
Organizations such as https://letsencrypt.org offer free certificates that must be renewed every 90 days.
When you visit https://www.google.com, for example, behind the scenes you’re making a request to Google’s servers, which in turn send a response back to you, rendering the famous Google Search landing page. This request-response relationship allows for a channel of communication between the user and the application. In figure 1, a bundle of data is sent to the application’s server in the form of a request, and when the server processes the request, it issues a bundle of data back in the form of a response.
This process is how most of your interaction on the internet is facilitated. A web server sends your browser web pages, images, and other resources on request. When you enter the URL you want to see in your browser, an HTTP request is sent to a physical computer elsewhere.
This request contains some information indicating whether you want to load a web page or send information to that computer. You may build a fancy application with many bells and whistles, but at the core lies a web server to handle its communication on the internet. In the next section, you start building your web server.
What does a web server receive from the client, and what does it send back? The web server receives requests from the client and sends back responses.
Initializing the application with npm. Before you get started with a Node.js web application, you need to initialize the project in your project folder in terminal. Open a terminal window, and create a new directory called simple_server with mkdir. You can initialize the project with npm init. NOTE: npm is Node.js’ package manager.
Your Node.js projects rely on this tool to install and build applications. You can learn more about npm and how it’s used at https://docs.npmjs.com.
Running the npm init command initiates a prompt to create a package.json file.
As the prompt explains, you’ll walk through configuring the most basic settings of your Node.js application in this file. For now, you can add main.js as the entry point, along with a short description and your name as the author, and elect to use the default values offered by pressing the Enter key until you reach the end of the prompt.
Then you’re asked to confirm your settings with a preview of your package.json file. Press Enter to confirm and return to the regular terminal prompt. Coding the application. When you installed Node.js, the core library was installed too. Within that library is a module called http. You’ll use this module to build your web server. In this section, you also use a package called http-status-codes to provide constants for use where HTTP status codes are needed in your application’s responses.
NOTE: Modules in Node.js are libraries of code that come packaged to offer specific functionality to your application. Here, the http module helps you communicate across the web by using HTTP. In your text editor, create a new file called main.js, and save it in the project folder called simple_server containing the package.json file you created earlier. This file will serve as the core application file, where your application will serve web pages to your users.
Within this project’s directory in terminal, run npm i http-status-codes -S to save the http-status-codes package as an application dependency. Before I analyze every aspect of what you’re about to build, take a look at all the code in listing 1.
The first line of code assigns the port number you’ll use for this application: 3000.
This number has no significance, and you can customize it with a few exceptions.
Ports 80 and 443 usually are reserved for HTTP and HTTPS, respectively. Then you use require to import a specific Node.js module called http and save it as a constant. This module is saved as a constant because you don’t plan on reassigning the variable.
You also require the http-status-codes package to provide constants representing HTTP status codes. Next, you use the http variable as a reference to the HTTP module to create a server, using that module’s createServer function, and store the resulting server in a variable called app.
NOTE: Using ES6 syntax, you structure callback functions with parameters in parentheses, followed by ⇒ instead of the function keyword. The createServer function generates a new instance of http.Server, a built-in Node.js class with tools for evaluating HTTP communication.
With this newly created server instance, your app is prepared to receive HTTP requests and send HTTP responses.
WARNING: These method names are case-sensitive. Using createserver, for example, will throw an error. The argument in createServer is a callback function that’s invoked whenever some event occurs within the server.
When the server is running and your application’s root URL (home page) is accessed, for example, an HTTP request event triggers this callback and allows you to run some custom code.
In this case, the server returns a simple HTML response.
You log that a request was received from the client and use the response parameter in the callback function to send content back to the user, from whom you first received a request.
The first line uses a writeHead method to define some basic properties of the response’s HTTP header. HTTP headers contain fields of information that describe the content being transferred in a request or response.
Header fields may contain dates, tokens, information about the origins of the request and response, and data describing the type of connection.
In this case, you’re returning httpStatus.OK, which represents a 200 response code, and an HTML content-type to indicate that the server received a request successfully and will return content in the form of HTML.
Following this block, you assign a local variable, responseMessage, with your response message in HTML. NOTE:200 is the HTTP status code for OK, used to indicate that no issue occurred in returning content in an HTTP response header. To get a list of other HTTP status codes, enter http.STATUS_CODES in the Node.js REPL shell. Use httpStatus.OK in place of the explicit number. Right below that line, you’re writing a line of HTML in the response with write and closing the response with end.
You must end your response with end to tell the server that you’re no longer writing content. Not doing so leaves the connection with the client open, preventing the client from receiving the response.
You also log your response at this point so you can see that a response was sent from the server itself. The last line of code takes the server instance, app, and runs the listen method to indicate that the server is ready for incoming requests at port 3000.
NODEJS HTTP SERVER
1 Require the http and http-status-codes modules. 2 Create the server with request and response parameters. 3 Write the response to the client. 4 Tell the application server to listen on port 3000. NOTE: The response object is used by Node.js and carried throughout the application as a way to pass information about the current client transaction from function to function.
Some methods on the response object allow you to add data to or remove data from the object; writeHead and write are two such functions.
- There your application is, in all its glory!
- Not so terrible.
- In only a few lines of code, you’ll also build a web server this way.
NOTE: If you don’t specify a port number, your operating system will choose a port for you. This port number is what you’ll soon use to confirm through your web browser that your web server is running. CALLBACKS IN NODE.JS.
- A callback is an anonymous function (a function without a name) that’s set up to be invoked as soon as another function completes.
The benefit of using callbacks is that you don’t have to wait for the original function to complete processing before running other code. Consider virtually depositing a check in your bank account by uploading a picture to your bank’s mobile app. A callback is equivalent to receiving a notification a couple of days later that the check was verified and deposited.
Callbacks on the server indicate when to respond to the client.
With this code in place, you’re ready to start your Node.js application from terminal.
Why should you use const instead of var to store the HTTP server in your application?
Because your server will continue to listen for communication from clients, it’s important not to reassign the variable representing the server.
In ES6, it has become convention to mark these objects as constants, not reassignable variables.
Running the application. The last step is an easy one.
Navigate to your project’s directory with terminal, and run node main in your terminal window.
Next, open any browser to the address localhost: 3000. You see a message indicating that the server has started.
Your terminal window should resemble figure 2. Running the a basic Node.js server. The browser window should greet you and the universe with salutations, as shown in figure 3. Congratulations! Your first Node.js web application is complete.
It’s big, and it’s about to get bigger and better. Display of your first web page. To stop the application, press Ctrl-C in your terminal window. You can also close the terminal window, but you may risk not shutting down the application properly, in which case the application could continue to run behind the scenes (requiring more command-line magic to kill the process).
When you navigate to http://localhost:3000/ while your server is running, what type of HTTP request are you making?
Nearly every request you can expect to make at this stage in the application’s development, including a request to http://localhost:300/, is an HTTP GET request.
You configured a new Node.js application via the package.json file. Using the http module and createServer method, with minimal effort you created a web server, which is a stepping stone to building robust applications with Node.js.
Through terminal, you were able to run a web-server application. Complete the “Try this” exercise to check your understanding. npm init interactively generates a package.json file, although you could create this file on your own.
Create a new package.json from scratch for the project in this lesson. Don’t use npm init; see whether you can construct a similar JSON-structured file.
That’s all for now. If you want to learn more about the book, you can check it out on Manning’s browser-based liveBook platform here. In this example we’ll show how to create an HTTP server using Node.js.
The server will listen on port 1337, and will send Hello, World! to the browser upon a GET request. Note that, instead of using port 1337, you can use any port number of your choice which is currently not in use by any other service.
The http module is a Node.js core module (a module included in Node.js’s source, that does not require installing additional resources).
The http module provides the functionality to create an HTTP server using the http.createServer() method.
The created server can then be accessed with the URL http://localhost:1337 or http://127.0.0.1:1337 in the browser. A simple web page will appear with a Hello, World! text at the top, as shown in the screenshot below:.
The Node.js framework is mostly used to create server-based applications.
The framework can easily be used to create web servers which can serve content to users.
We will have a look at how we can create a basic web server application using Node js. Let’s look at an example of how to create and run our first Node js application. Our application is going to create a simple server module which will listen on port no 7000.
In this line of code, we are creating a server application which is based on a simple function.
This function is called whenever a request is made to our server application. When a request is received, we are saying to send a response with a header type of ‘200.’ This number is the normal response which is sent in an http header when a successful response is sent to the client. In the response itself, we are sending the string ‘Hello World.’.
We are then using the server.listen function to make our server application listen to client requests on port no 7000.
You can specify any available port over here.
If the command is executed successfully, the following Output will be shown when you run your code in the browser.
From the output,. You can clearly see that if we browse to the URL of localhost on port 7000, you will see the string ‘Hello World’ displayed in the page.
Because in our code we have mentioned specifically for the server to listen on port no 7000, we are able to view the output when browsing to this url.
Here is the code for your reference. Making a GET Request to get the data from another site is relatively very simple in Node.js.
To make a Get request in the node, we need to first have the request module installed. This can be done by executing the following line in the command line.
npm install request. The above command requests the Node package manager to download the required request modules and install them accordingly. When your npm module has been installed successfully, the command line will show the installed module name and version:
In the above snapshot, you can see that the ‘request’ module along with the version number 2.67.0 was downloaded and installed.
Now let’s see the code which can make use of this ‘request’ command. We are using the ‘request’ module which was installed in the last step.
We are making a GET Request to www.google.com and subsequently calling a function when a response is received.
When a response is received the parameters(error, response, and body) will have the following values. Error – In case there is any error received when using the GET request, it will be recorded here. Response- The response will have the http headers which are sent back in the response.
Body- The body will contain the entire content of the response sent by Google. In this, we are just writing the content received in the body parameter to the console.log file.
So basically, whatever we get by going to www.google.com will be written to the console.log.
Here is the code for your reference. The Node.js framework can be used to develop web servers using the ‘http’ module.
The application can be made to listen on a particular port and send a response to the client whenever a request is made to the application.
The ‘request’ module can be used to get information from web sites. The information would contain the entire content of the web page requested from the relevant web site.
Run the Application
The following is an excerpt from the bookGet Programming with Node.js, published by manning.com. You can purchase the book here at a 37% discount by using the code fccwexler. This article is a practical introduction to using Node.js. We’re going to go over installing Node.js, learn about npm, and then we’re going to build a Node.js module and jump right in to initializing a web server.
Feel free to follow along at home as you read! Node.js is growing in popularity and support. Because of this, new versions to download are being deployed quite frequently, and it’s important to stay up to date with the latest versions to see how they may benefit or otherwise impact the applications you’re building.
At the time of writing, the version of Node.js to download is 7.6 or greater.
NOTE: The release of Node.js 7.6 comes with support for ES6 syntax.
There are a couple of ways to download and install Node.js, all of which are listed on the Node.js main site. Because Node.js is platform-independent, you can download and install it on macOS, Windows, or Linux and expect full functionality. The simplest way to install Node.js is to go to the download link and follow the instructions and prompts to download the installer for the latest version of Node.js.
NOTE: When you install Node.js, you also get npm, the Node.js ecosystem of external libraries (multiple files of code other people wrote) that can be imported into your future projects.
You’ll learn more about npm in the next section. Node.js installer page. When the installer file is downloaded, double-click the file from your browser’s download panel or from your computer’s download folder.
The installer will open a new window that looks like Figure 1 and write all necessary files and core Node.js libraries to your system.
You may be asked to accept licensing agreements or give the installer permission to install Node.js onto your computer.
Follow the prompts to click through the installation. Node.js writing to your machine. You’ll be working mostly in your computer’s terminal, which is built-in software used to navigate and run commands on your computer without a graphical interface. This book teaches using the Unix terminal (Bash) commands. Those of you who are Windows users can follow along using Window’s CMD terminal window (you may need to look up command-equivalents throughout the book).
You can reference this table comparing Windows and Unix commands. To make things easier on Windows, you can download and install an additional Bash terminal called GitBash from git-scm.com.
This information is shown in the final window in the installer. The installer attempts to add these directory locations to your system’s PATH. Your computer’s PATH variable is the first place the terminal will look for resources used in development. Think of it like your computer’s index for quickly finding the tools you need.
By adding these tools’ original file path or directory locations to the PATH variable, terminal won’t have any problems finding them.
If you experience any problems starting Node.js in your terminal, follow the installation steps here. Now that you have Node.js installed, let’s use terminal to make sure everything is installed correctly.
Open terminal (or GitBash) and type the following command at the prompt: node-v. The output of this command should show you the version of Node.js you’ve just installed. Similarly, you can check the version of npm that you’ve installed by running the command npm -v at the command prompt.
NOTE: If your terminal responds with an error or with nothing at all, it’s possible that your installation of Node.js was not successful. In the case of an error, try copying and pasting that error into a search engine to look for common solutions or simply try repeating the installation process.
Although text editors come in many different forms and can be used to make non-code files as well, text editors designed specifically for developers often come prepackaged with helpful tools and plugins.
I recommend installing the Atom text editor, which you can download at atom.io. TIP: If you ever forget where you installed Node.js or npm, you can open a command window and type either which node or which npm at the prompt to see the corresponding location. From a Windows command-line prompt, use where in place of which.
Imagine that you want to build an application for your city’s community-supported agriculture (CSA) club.
Through this application, users could subscribe to receive food from local farms and distributors.
The application ensures that your community gets healthy food and stays connected. You plan to use Node.js to build this web application and you want to start by verifying users’ zip codes to see if they live close enough for delivery.
The question is: will you need to build your own tool to make this possible? Luckily for us, the answer is no, npm can be used to install Node.js packages, libraries of code others have written that you can use to add specific features to your application. In fact, there’s a package for verifying locations based on zip codes. We’ll take a closer look at that package and how to install it in a little bit.
Node as a web server using HTTP
Each file, whose code is collectively related, is called a module. Let’s look at our app again and add some positive messages to it.
You can create a file called messages.js with the following code:.
Keeping these messages separate from the code you’ll write to display them will make your code more organized.
To manage these messages in another file, you need to change the let variable definition to use the exports object, like so:.
module is both the name of the code files in Node.js and one of its global objects. Using exports is essentially a shorthand for module.exports.
You can test this by creating another file called printMessages.js, whose purpose is to loop through the messages and log them to your console with the code in listing 1. First, require the local module by using the require object and the module’s filename (with or without a .js extension). Then, refer to the module’s array by the variable set up in printMessages.js. log messages to console in printMessages.js.
Require the local messages.js module. Refer to the module’s array through messageModule.messages. require is another Node.js global object used to locally introduce methods and objects from other modules. Node.js interprets require('./messages'); to look for a module called messages.js within your project directory and allow code within printMessages.js to use any properties added to the exports object.
Next, we’ll use npm, another tool for adding modules to your project. With your installation of Node.js, you also got Node Package Manager (npm). As the name suggests, npm is responsible for managing the external packages (modules others have built and made available online) in your application.
Creating a Node.js Module
Throughout application development, npm will be used to install, remove, and modify these packages. Entering npm -l in your terminal brings up a list of npm commands with brief explanations. Listing 2 contains a few npm commands that you’ll want to know about.
Npm commands to know. Initializes a Node.js application and creates a package.json file. npm install
Runs your Node.js application (provided the package.json file is set up to use this command). npm stop will quit the running application. When using the npm install
Appending --global installs the package globally on your computer to be used anywhere within terminal.
These command extensions, called flags, have the shorthand forms of -S and -g, respectively.
Should a project call for it, the npm install express -S can be used to install the Express.js framework, and npm install express-generator -g to install the Express.js generator for use as a command-line tool.
Throughout your development with Node.js, you’ll hear the terms module and package thrown around a lot.
Packages may contain multiple modules or a single module. Packages are used to group together files offering relevant tools. NOTE: “Dependencies” are Node.js modules used by an application or another module.
If a package is considered an application dependency, it must be installed (at the version specified by the application) before the application can be expected to run successfully.
If there’s some functionality you’d like to incorporate into your application, there’s likely a package you can find online at npmjs.com to perform that task.
Let’s go ahead and add the ability to find where your users are located based on their zip code.
To do this, we’ll need to install the cities package, built to convert text addresses into location coordinates.
We’ll need to properly initialize a Node.js project and create a package.json file used by npm for installing cities, which we will do in the next section.
Quick Check Exercise: Which flag do you use if you want to install a package globally on your computer? Every Node.js application or module will contain a package.json file to define the properties of that particular project.
This file lives at the root level of your project. Typically, this file is where you’ll specify the version of your current release, the name of your application, and the main application file.
This file is important for npm to save any packages to the node community online. To get started, create a folder called zip_connection, navigate to your project directory in terminal, and use the npm init command to initialize your application.
You’ll be prompted to fill out the name of your project, the application’s version, a short description, the name of the file from which you’ll start the app (entry point), test files, git repositories, your name (author), and a license code.
Once you confirm all these changes, you should see a new package.json file in your project directory resembling the contents of Listing 3. Result of your package.json file in your zip_connection project.
This example package.json contains a name, version, description, starting file, custom scripts, an author, and license. Now your application has a starting point for saving and managing application configurations and packages. You should be able to install cities by navigating to your project folder and running the following in terminal:.
Also, with this installation, your project folder will have just gained a new folder called node_modules.
The code contents of the cities package you just installed lives in this folder. TIP: The --save flag will save the cities package as a dependency for this project.
Because your node_modules folder will grow in size, it is not recommended to include it when you share the project code online.
However, anyone who downloads the project can enter npm install to automatically install all the project dependencies listed in this file.
Test out this new package by adding the lines in Listing 4 to main.js. We’ll start by requiring the locally installed cities package and make it available in this file. Then we’ll use the zip_lookup method from the cities package to find a city by its zip code. The result is stored in a variable called myCity.
Implementing the cities package in main.js. The code above does the following:. Require the cities package. Store the resulting city from using the zip_lookup method.
Log the results to your console. The resulting data from that zip code is printed to console as shown in Listing 5.
Quick Check Exercise: Which terminal command initializes a Node.js application with a package.json file?
This section covers some basic functions of the http module, a Node.js library of code used for handling requests over the internet.
Web servers are the foundation of most Node.js web applications. They allow you to load images and HTML web pages to users of your app. Let’s consider that application that we’re working on to connect users from the same zip code.
Before you deliver the complete application, the community might like to see a simple site with the flexibility to improve and add features in the future. How long do you think it will take you to build a prototype? With Node.js, you can use the http module to get a web server with sufficient functionality built within hours. Before getting started, let’s discuss some important web server concepts.
After all, the final product will look and feel a lot better if you have clear expectations for the result ahead of time. A web server is software designed to respond to requests over the internet by loading or processing data.
Think of a web server like a bank teller, whose job is to process your request to deposit, withdraw, or simply view money in your account. Just as the bank teller follows a protocol to ensure that they process your request correctly, web servers follow the Hypertext Transfer Protocol (HTTP), a standardized system globally observed for the viewing of web pages and sending of data over the internet.