Lesson 8. Setting up an app with Express.js

Building a web application has become a simpler task with the addition of web frameworks. A web framework in Node.js is a module that offers structure to your application. Through this structure, you can easily build and customize the way your application feels without worrying about building certain features from scratch, such as serving individual files. By the end of this lesson, you’ll know where to begin with web frameworks and how the one used in this book, Express.js, can reduce the time it takes you to get your application running.

This lesson covers

  • Setting up a Node.js application with Express.js
  • Navigating a web framework
Consider this

Your static web app from unit 1 is a success. The cooking community wants you to add more functionality and serve more web pages. You realize that your application isn’t fully prepared to handle more routes, let alone handling errors or serving other types of assets. Could there be an easier way to start development with some structure already in place?

Luckily, you can install a web framework with your Node.js application. Express.js, the framework you use in this book, handles a lot of the tasks most applications need right out of the box, such as error handling and static-asset serving. The more familiar you get with this framework’s methods and keywords, the faster you can build your applications.

8.1. Installing the Express.js package

Express.js increases development speed and provides a stable structure on which to build applications. Like Node.js, Express.js offers tools that are open-source and managed by a large online community.

First, I’ll talk about why Express.js is the web framework you should learn. With each passing year, Node.js gains new frameworks, some of which provide convincing reasons to switch to its library. Express.js came out in 2010, and since then, other reliable frameworks have grown in popularity. Table 8.1 lays out some other frameworks you can look into.

Table 8.1. Node.js frameworks to know

Node.js frameworks

Description

Koa.js Designed by developers who built Express.js with a focus on a library of methods not offered in Express.js (http://koajs.com/)
Hapi.js Designed with a similar architecture to Express.js and a focus on writing less code (https://hapijs.com/)
Sails.js Built on top of Express.js, offering more structure, as well as a larger library and less opportunity for customization (https://sailsjs.com/)
Total.js Built on the core HTTP module and acclaimed for its high-performance request handling and responses (https://www.totaljs.com/)
Note

For more information about Node.js web frameworks, you can view an updated list of GitHub repositories at http://nodeframework.com/.

Ultimately, a framework is intended to help you overcome some common development challenges in building a web application from scratch. Express.js is the most used framework in the Node.js community, ensuring that you find the support you need compared with the support offered by other, newer frameworks. Although I recommend using Total.js for its performance and scalability ratings, it’s not necessarily the best framework to start with.

Because you’re working with Node.js to build a web application for the first time, you need some tools to help you along the way. A web framework is designed to offer some of the common tools used in web development. Express.js provides methods and modules to assist with handling requests, serving static and dynamic content, connecting databases, and keeping track of user activity, for example. You find out more about how Express.js provides this support in later lessons.

Express.js is used by new and professional Node.js developers alike, so if you feel overwhelmed at any time, know that thousands of others can help you overcome your development obstacles.

Now you’re ready to jump into initializing an application with Express.js. To begin, you need to initialize your application by creating a new project directory called first_express_project, entering that directory within a new terminal window, and entering npm init. You can follow the prompt to save main.js as the entry point and to save all the other default values.

Note

As discussed in lesson 1, initializing a new project creates a package.json file with which you can define some attributes of your application, including the packages you download and depend on.

Because Express.js is an external package, it doesn’t come preinstalled with Node.js. You need to download and install it by running the following command within your project directory in terminal: npm install express --save.

Note

At this writing, the latest version of Express.js is 4.16.3. To ensure that your version of Express.js is consistent with the one used in this book, install the package by running npm install [email protected] --save.

Warning

If you try to install Express.js in a specific project before you create package.json, you may see an error complaining that there’s no directory or file with which the installation can complete.

Use the --save flag so that Express.js is listed as an application dependency. In other words, your application depends on Express.js to work, so you need to ensure that it’s installed. Open package.json to see this Express.js package installation under the dependencies listing.

Tip

If you want to access the Express.js package documentation from your terminal window, type npm docs express. This command opens your default web browser to http://expressjs.com.

In the next section, you create your first Express.js application.

Quick check 8.1

Q1:

What happens if you don’t use the --save flag when installing Express.js for your application?

QC 8.1 answer

1:

Without the --save flag, your Express.js installation won’t be marked as an application dependency. Your application will still run locally, because Express.js will be downloaded to your project’s node_modules folder, but if you upload your application code without that folder, there’s no indication in your package.json file that the Express.js package is needed to run your application.

 

8.2. Building your first Express.js application

To start using Express.js, you need to create a main application file and require the express module. Save the code in listing 8.1 to a file called main.js within your project.

You require Express.js by referring to the module name express and storing it as a constant. express offers a library of methods and functionality, including a class with built-in web server functionality. The express webserver application is instantiated and stored in a constant to be referred to as app. Throughout the rest of the project, you’ll use app to access most of Express.js’ resources.

As in the first capstone project, Express.js offers a way to define a GET route and its callback function without building out an extra module. If a request is made to the home page, Express.js catches it and allows you to respond.

A response in plain text is sent to the browser. Notice the Express.js method send, which behaves similarly to write from the http module. Express.js also supports http module methods. Remember to use end to complete your response if you use write. Finally, you set up the application to listen for requests on port 3000 of your local host and ask for a helpful message to be logged to your console when the application is running successfully.

Listing 8.1. Simple Express.js web application in main.js
const port = 3000,
  express = require("express"),                                    1
  app = express();                                                 2

app.get("/", (req, res) => {                                       3
  res.send("Hello, Universe!");                                    4
})
.listen(port, () => {                                              5
  console.log(`The Express.js server has started and is listening
  on port number: ${port}`);
});

  • 1 Add the express module to your application.
  • 2 Assign the express application to the app constant.
  • 3 Set up a GET route for the home page.
  • 4 Issue a response from the server to the client with res.send.
  • 5 Set up the application to listen at port 3000.

Give it a shot. Make sure that you’re in your project directory on your command line. Run node main, and go to http://localhost:3000. If you see Hello, Universe! on the screen, you’ve built your first successful Express.js application.

Installing and using nodemon

To see your application server code changes in effect, you need to restart the server in terminal. Close your existing server by pressing Command-D (Ctrl-C for Windows) and entering node main.js again.

The more changes you apply to your application, the more tedious this task becomes. That’s why I recommend installing the nodemon package. You can use this package to start your application the first time and automatically restart it when application files change.

To install nodemon globally, enter npm i nodemon -g. You may need to prepend that command with sudo or run it in terminal as an administrator.

Alternatively, you can install nodemon as a development dependency (devDependency) or a resource that you use only during development of an application. Run npm i nodemon -- save-dev or npm i nodemon -D. nodemon starts with your npm start script (discussed in lesson 11). The benefit of installing as a devDependency is that each project has its own nodemon modules, reflecting the most up-to-date version of the package at the time of development.

When nodemon is installed, it’s simple to use: nodemon picks up on the main property in your package.json. Your package.json should also be modified to include the npm start script. Add "start": "nodemon main.js", to the scripts section in package.json so that you may run your application using nodemon with npm start. Go to your project directory in terminal, and enter nodemon. This command launches your application, and any future changes you make signal nodemon to restart without your needing to enter another command.

You can shut down the server by pressing the same key combination (Command-D or Ctrl-C for Windows) in the nodemon window in terminal.

Note

The express constant is still used for some Express.js tools related to configuring your application. app is used mainly for anything created for the application’s movement of data and user interaction.

In the next section, I talk about some of the ways that Express.js offers support as a web framework.

Quick check 8.2

Q1:

What’s the difference between the express and app constants?

QC 8.2 answer

1:

app represents most of your application, the routes, and access to other modules. express represents a wider range of methods that aren’t necessarily scoped to your application. express could offer a method to analyze or parse some text on which your application doesn’t necessarily depend.

 

8.3. Working your way around a web framework

A web framework is designed to do a lot of the tedious tasks for you and leave you with an intuitive structure for customizing your app. Express.js provides a way to listen for requests to specific URLs and respond by using a callback function.

A web framework like Express.js operates through functions considered to be middleware because they sit between HTTP interaction on the web and the Node.js platform. Middleware is a general term applied to code that assists in listening for, analyzing, filtering, and handling HTTP communication before data interacts with application logic.

You can think of middleware as being like a post office. Before your package can go into the delivery network, a postal worker needs to inspect the size of your box and to ensure that it’s properly paid for and adheres to delivery policies (nothing dangerous in your package). See the diagram on middleware in figure 8.1.

Figure 8.1. Express.js stands between the HTTP requests and your application code.

Note

Middleware can come in smaller packages than Express.js. Some play a security role in checking incoming requests before data passes through to the core application.

Because you’re still dealing with HTTP methods, the overall interaction between your application and the browser doesn’t change much from your application that uses the http module in unit 1. You get the same request and response objects, containing a lot of rich information about the sender and its contents. Express.js offers methods that make it easier for you to get that information.

In addition to the send method on the response object, Express.js provides simpler ways to pull and log data from the request body. Add the code in the next listing to your GET route handler in main.js.

Listing 8.2. Request object methods in Express.js in main.js
console.log(req.params);         1
console.log(req.body);
console.log(req.url);
console.log(req.query);

  • 1 Access request parameters.

From the request, you can pull the values in table 8.2.

Table 8.2. Request object data items

Request data object

Description

params Allows you to extract IDs and tokens from the URL. When you learn about RESTful routes in unit 4, this request attribute allows you to identify which items are being requested in an e-commerce site or what user profile you should navigate to.
body Contains much of the contents of the request, which often includes data coming from a POST request, such as a submitted form. From the request body, you can collect information quickly and save it in a database.
url Provides information about the URL being visited (similar to req.url in unit 1’s basic web server).
query Like body, lets you pull data being submitted to the application server. This data isn’t necessarily from a POST request, however, and is often requested in the URL as a query string.

Upon restarting your application and visiting http://localhost:3000, you see these values logged to your server’s terminal window. You explore how to make better use of the request body when you learn about Express.js routes in lesson 9.

Tip

A query string is text represented as key/value pairs in the URL following a question mark (?) after the hostname. http://localhost:3000?name=jon, for example, is sending the name (key) paired with jon (value). This data can be extracted and used in the route handler.

Quick check 8.3

Q1:

Why do most developers use web frameworks instead of building web applications from scratch?

QC 8.3 answer

1:

Web frameworks make development work a lot easier. Web development is fun, and the best parts aren’t the tedious tasks that are most subject to errors. With web frameworks, developers and businesses alike can focus on the more interesting parts of applications.

 

Summary

In this lesson, you learned how to initialize an Express.js project and started a simple application that said hello in your web browser. You also learned about Express.js as a web framework and saw how you’ll benefit from its methods moving forward. In lesson 9, you apply some Express.js methods in building a routing system.

Try this

Change the get method in your index.js file to post. Restart your application, and see how your application behaves differently when you try to access the home page at http://localhost:3000. You should see a default error message from Express, telling you that there’s no GET route for /.

The reason is that you changed the request method you’re listening for. If you make a curl POST request to the home page, you see your original response content.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.214.215