Building an Express Web Application - kollektivesplagiieren/innovative-commercial-market GitHub Wiki

Introduction to Express

Express wraps the Connect module in several ways. The app.use() method is used to mount a middleware function. Inside the middleware function, the res.send() method is then used to send the response back. The res.send() method is basically an Express wrapper that sets the Content-Type header according to the response object type and then sends a response back using the Connect res.end() method.

When passing a buffer to the res.send() method, the Content-Type header will be set to application/octet-stream. When passing a string, it will be set to text/html and when passing an object or an array, it will be set to application/json.

The application object

The application object contains the following methods to help you configure your application:

  • app.set(name, value): This is used to set environment variables that Express will use in its configuration.

  • app.get(name): This is used to get environment variables that Express is using in its configuration.

  • app.engine(ext, callback): This is used to define a given template engine to render certain file types, for example, you can tell the EJS template engine to use HTML files as templates like this: app.engine('html', require('ejs').renderFile).

  • app.locals: This is used to send application-level variables to all rendered templates.

  • app.use([path], callback): This is used to create an Express middleware to handle HTTP requests sent to the server. Optionally, you'll be able to mount middleware to respond to certain paths.

  • app.VERB(path, [callback...], callback): This is used to define one or more middleware functions to respond to HTTP requests made to a certain path in conjunction with the HTTP verb declared. For instance, when you want to respond to requests that are using the GET verb, then you can just assign the middleware using the app.get() method. For POST requests you'll use app.post(), and so on.

  • app.route(path).VERB([callback...], callback): This is used to define one or more middleware functions to respond to HTTP requests made to a certain unified path in conjunction with multiple HTTP verbs. For instance, when you want to respond to requests that are using the GET and POST verbs, you can just assign the appropriate middleware functions using app. route(path).get(callback).post(callback).

  • app.param([name], callback): This is used to attach a certain functionality to any request made to a path that includes a certain routing parameter. For instance, you can map logic to any request that includes the userId parameter using app.param('userId', callback).

The request object

The request object also provides a handful of helping methods that contain the information you need about the current HTTP request. The key properties and methods of the request object are as follows:

  • req.query: This is an object containing the parsed query-string parameters.

  • req.params: This is an object containing the parsed routing parameters.

  • req.body: This is an object used to retrieve the parsed request body. This property is included in the bodyParser() middleware.

  • req.param(name): This is used to retrieve a value of a request parameter. Note that the parameter can be a query-string parameter, a routing parameter, or a property from a JSON request body.

The request object contains many more methods and propertiesbook, but these methods are what you'll usually use in a common web application.

The response object

The response object is frequently used when developing an Express application because any request sent to the server will be handled and responded using the response object methods. It has several key methods, which are as follows:

  • res.status(code): This is used to set the response HTTP status code.

  • res.set(field, [value]): This is used to set the response HTTP header.

  • res.cookie(name, value, [options]): This is used to set a response cookie. The options argument is used to pass an object defining common cookie configuration, such as the maxAge property.

  • res.redirect([status], url): This is used to redirect the request to a given URL. Note that you can add an HTTP status code to the response. When not passing a status code, it will be defaulted to 302 Found.

  • res.send([body|status], [body]): This is used for non-streaming responses. This method does a lot of background work, such as setting the Content-Type and Content-Length headers, and responding with the proper cache headers.

  • res.json([status|body], [body]): This is identical to the res.send() method when sending an object or array. Most of the times, it is used as syntactic sugar, but sometimes you may need to use it to force a JSON response to non-objects, such as null or undefined.

  • res.render(view, [locals], callback): This is used to render a view and send an HTML response.

The response object also contains many more methods and properties to handle different response scenarios.

External middleware

The Express core is minimal, yet the team behind it provides various predefined middleware to handle common web development features. These types of middleware vary in size and functionality and extend Express to provide a better framework support. The popular Express middleware are as follows:

  • Morgan: This is an HTTP request logger middleware.

  • body-parser: This is a body-parsing middleware that is used to parse the request body, and it supports various request types.

  • method-override: This is a middleware that provides HTTP verb support such as PUT or DELETE in places where the client doesn't support it.

  • Compression: This is a compression middleware that is used to compress the response data using gzip/deflate.

  • express.static: This middleware used to serve static files.

  • cookie-parser: This is a cookie-parsing middleware that populates the req.cookies object.

  • Session: This is a session middleware used to support persistent sessions.

There are many more types of Express middleware that enable you to shorten your development time, and even a larger number of third-party middleware.

Configuring an Express application

robust feature of Express is the ability to configure your application based on the environment it's running on. For instance, you may want to use the Express logger in your development environment and not in production, while compressing your responses body might seem like a good idea when running in a production environment.

To achieve this, you will need to use the process.env property. The process.env is a global variable that allows you to access predefined environment variables, and the most common one is the NODE_ENV environment variable. The NODE_ENV environment variable is often used for environment-specific configurations.

It is recommended that you set the NODE_ENV environment variable in your operating system prior to running your application.

Rendering views

A very common feature of web frameworks is the ability to render views. The basic concept is passing your data to a template engine that will render the final view usually in HTML. In the MVC pattern, your controller uses the model to retrieve the data portion and the view template to render the HTML output as described in the next diagram. The Express extendable approach allows the usage of many Node.js template engines to achieve this functionality.

Express has two methods for rendering views: app.render(), which is used to render the view and then pass the HTML to a callback function, and the more common res.render(), which renders the view locally and sends the HTML as a response.

Rendering EJS views

EJS views basically consist of HTML code mixed with EJS tags and have the .ejs extension. When you'll use the res.render() method, the EJS engine will look for the template in the views folder, and if it finds a complying template, it will render the HTML output.

The `<%= %> tag the way to tell the EJS template engine where to render the template variables.

Serving static files

Serving static files In any web application, there is always a need to serve static files. Fortunately, Express comes prebundled with the express.static() middleware, which provides this feature.

The express.static() middleware takes one argument to determine the location of the static folder. Notice how the express.static() middleware is placed below the call for the routing file. This order matters because if it were above it, Express would first try to look for HTTP request paths in the static files folder. This would make the response a lot slower as it would have to wait for a filesystem I/O operation.

Configuring sessions

Sessions are a common web application pattern that allows you to keep track of the user's behavior when they visit your application. The express-session module will use a cookie-stored, signed identifier to identify the current user. To sign the session identifier, it will use a secret string, which will help prevent malicious session tampering. For security reasons, it is recommended that the cookie secret be different for each environment,

⚠️ **GitHub.com Fallback** ⚠️