Getting started with Express

Express describes itself as a fast, unopinionated, minimalist web framework for Node.js. Express is a very powerful and flexible framework that operates on top of Node.js, but still allows you access to all of the features of Node. At its core, Express operates as a set of routing and middleware functionality.

We'll get into routing and middleware in detail in later chapters. Basically, routing handles web requests. Middleware consists of functions that have access to the request and response objects and call the next piece of middleware in the stack.

If it's so easy to just throw up a web server using Node,js, why do we need something like Express?

The answer is, you don't. You could, all on your own, build a fully featured web application by just writing your own Node.js. Express has done a lot of the grunt work and heavy lifting for you. Because of the middleware that's easy to plus into Express, adding things such as security, authentication, and routing is fairly simple. And, who wants to build that stuff from scratch when you have an exciting new web application to build?

Installing Express

Of course, you will use NPM to install Express. There are two ways to do this.

The standard method is just to use NPM to pull the Express project down and add a reference to it in package.json. This is just adding the module into a Node.js project. You will build an application script, require it in Express, and utilize it in that WAR file.

The second method is to install the Express generator and use it to generate a starter web application. This method is simple to employ but it does structure your whole application, including folder structure, for you. Some people would prefer to do all of this on their own to get their setup precisely a certain way.

We will try both methods, and use the Express generator to build the framework for the Single Page Application that you will build throughout the rest of this book.

Standard method

Again, the standard method will just be to pull the module down and add it to your project. In your console, in the directory with the package.json file we just created, type the following command:

$ npm install express --save

Tip

On a Mac, you may have to type sudo before npm install. If you're on a Mac, I would just go ahead and use sudo each type you are installing something with NPM.

The -save part tells npm to add Express as a dependency to your package.json file. Go ahead and open your package.json file and look at the dependencies section.

If you are using git or another source control system to share a code base with other developers, you, typically, will not store the dependencies in the remote repository. Instead, the package.json file will hold a reference to the required modules and their version.

Another developer can pull down your code, run npm install, and install all of the dependencies.

If you look in the folder where your package.json file resides, you will see a new folder called node_modules. This is where all of your dependencies installed with npm are stored. It's important not to move this or change it as the require function will look in here for modules. Typically, this folder will be added to a .gitignore file to ensure that its files aren't stored on a remote git repository.

Express generator

There is another method of setting up an Express application. Express has created a generator that is a tool for rapidly setting up the framework for an Express application. It assumes some common conventions used in Express applications and configures things such as the main application, the package,json, and even the directory structure.

The generator is installed globally rather than in a specific project using the following command:

$ npm install express-generator -g

The -g tells NPM to install the module and its dependencies globally. They won't be installed in the npm_modules folder in your project, but in a global modules folder on your system.

Setting up your Express application

Now that we have the express generator installed globally, let's use it to start building the application we'll be building out in the rest of the book. Pick a folder where you want this project to live. The Express generator will create a new folder inside this folder, so it's fine if it is a home or projects folder containing other things.

Navigate to this folder in your console using the following command:

$ express -e giftapp
   create : giftapp
   create : giftapp/package.json
   create : giftapp/app.js
   create : giftapp/public
   create : giftapp/public/javascripts
   create : giftapp/public/images
   create : giftapp/routes
   create : giftapp/routes/index.js
   create : giftapp/routes/users.js
   create : giftapp/public/stylesheets
   create : giftapp/public/stylesheets/style.css
   create : giftapp/views
   create : giftapp/views/index.ejs
   create : giftapp/views/error.ejs
   create : giftapp/bin
   create : giftapp/bin/www
   install dependencies:
     $ cd giftapp && npm install
   run the app:
     $ DEBUG=giftapp:* npm start

As you can see, the express generator has created a number of files including app,js, your main app file.

The -e modifier we typed after the express command told the generator that we want to use ejs (embedded JavaScript) frontend templates. Express supports a number of templating languages, including Handlebars and Jade. If you add no modifier, the Express generator will assume you want to use Jade. For this project, we will use ejs, which is essentially real HTML with embedded JavaScript code.

The final output of the generator tells you the next steps you need to actually stand up your application. Navigate to your new giftapp directory and run npm install (remember sudo if you're on a Mac or Linux box). The npm install command at this point might take a few minutes as it's installing a number of dependencies.

The next command starts your new Express application in DEBUG mode—you will see all requests logged to the console. Navigating to localhost:3000 in your browser will display a Welcome to Express page.

Congratulations, this page is being served from your very own robust Express web application. It's not doing much yet, but a lot of pieces are already in place for you.

Exploring the main script

Open giftapp's new package.json file. Note the following scripts object:

"scripts": { 
  "start": "node ./bin/www" 
} 

This is saying that when the npm start is run, the script that's actually invoked is at ./bin/www. So, let's open the www file in your bin directory and take a look.

You'll see that this file is requiring a number of things, including app.js; this is your main application file:

var app = require('../app'); 

The next bit of code set's the port number of the app. It looks to see if there's an environment variable set containing the desired port number. If not, it sets it to 3000. When deploying an application to production, typically, you will use port 80 for HTTP or port 443 for HTTPS:

var port = normalizePort(process.env.PORT || '3000'); 
app.set('port', port); 

The next bit creates the server and starts listening on the correct port:

var server = http.createServer(app); 
... 
server.listen(port); 

For now, we'll skip over the rest of this file and take a look at what's in the app.js file. Go ahead and open it up.

Looking at the main application

App.js is the main application file that loads the routes and middleware and configures the application. There are a number of important sections of this file. In general, in Express applications, the order of loading and utilization, and the order middleware is invoked in this file, is important. Let's take a look.

Loading dependencies

When you open app.js, you will first encounter a number of calls to the require function, as follows:

var express = require('express'); 
var path = require('path'); 
var favicon = require('serve-favicon'); 
var logger = require('morgan'); 
var cookieParser = require('cookie-parser'); 
var bodyParser = require('body-parser'); 
var routes = require('./routes/index'); 
var users = require('./routes/users'); 

This system is known as CommonJS. The first set of modules includes the dependencies, such as Express, and a parser for cookies. The routes and users modules were created by the Express generator for routing. The routes you create will be required in the main file as well.

Configuring the application

Next, an app variable is declared by invoking the express function, and a couple of configuration variables are set, as follows:

var app = express(); 
... 
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'ejs'); 

The first configuration, views, tells Express where to look for the view templates. These are the templates that are normally rendered into HTML as the result of requests to the web application.

The second configuration sets the view engine. As we discussed earlier, we will use ejs or embedded JavaScript templates.

Application-level middleware

The next thing we will see in this file is a bunch of calls to the app object's use function, which is as follows:

app.use(logger('dev')); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 
app.use(express.static(path.join(__dirname, 'public'))); 
app.use('/', routes); 
app.use('/users', users); 
// catch 404 and forward to error handler 
app.use(function(req, res, next) { 
  var err = new Error('Not Found'); 
  err.status = 404; 
  next(err); 
}); 

In Express, calls to the application object's use function are application-level middleware. Requests sent to the application will execute every function matching the path set in app.use. If no path is set, the middleware function defaults to the root path /and will be invoked for every request.

For example, app.use(cookieParser()); means that the cookieParser function will be invoked for every request sent to the application because it defaults to the root path. However, app.use('/users',users); will only apply when the request begins with /users.

Middleware is invoked in the order it's declared. This will become very clear later, when we add authentication to our application, or want to handle POST data. If you don't parse cookies before you try to manage a request requiring authentication, it won't work.

Our first Express route

Express uses a mechanism called routing, using its Router object, to handle HTTP requests, such as those from web browsers. In a later chapter, we will take a more in-depth look at Express routing. It bears examining the first route that the Express generator created for us. Open your routes/index.js file, as shown in the following code block:

var express = require('express'); 
var router = express.Router(); 
 
/* GET home page. */ 
router.get('/', function(req, res, next) { 
  res.render('index', { title: 'Express' }); 
}); 
module.exports = router; 

To create a new set of routes, we must create a new router object by invoking the Expresses Router function. You will see that we require Express first, then do exactly that.

The next expression is a call to the router object's get function. This, in Express, is router-level middleware. This function sets up middleware, in the form of the enclosed anonymous function, which responds to HTTP GET requests, such as typing a URL in a browser's address bar or clicking on a link.

The first argument to the function is a path to match. When the path matches, in this case the root path, the function is invoked. The anonymous function here receives the request object, the response object, and the next object.

The function invokes the response object's render function. This function looks in the views directory for a template called index and renders it, passing it the object in the second argument. The template has access to all the properties of that object, in this case, just the title, and can render them to in the response.

Finally, we will see the module.exports=router; expression. This allows the Node.js module system to load this code using the required function and assign the router object to a variable. Near the top of our app.js file, you'll see varroutes=require('./routes/index');.

Rendering the first view

When you started the Express server, navigated to localhost:3000, and saw the default Express page, what happened?

The request came into the web application and was routed to index based on the request type, GET, and the path, /. The middleware then called the response object's render function and told it to get the index template, passing it an object with a property called title.

Open your views/ index.ejs file to see the following template code:

<!DOCTYPE html> 
<html> 
  <head> 
    <title><%= title %></title> 
    <link rel='stylesheet' href='/stylesheets/style.css' /> 
  </head> 
  <body> 
    <h1><%= title %></h1> 
    <p>Welcome to <%= title %></p> 
  </body> 
</html> 

If you've used other dynamic templating languages before, you probably already understand that this is normal HTML that contains some dynamic elements. Those dynamic elements that are contained by <%...%> are processed by the server. These tags are not sent to the browser, just clean HTML.

In this case, the three tags are identical, all rendering the title property of the object passed in the call to the response object's render method. As a quick experiment, change the value of the title passed in.

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

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