Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Introduction to Express.js Framework

Tech May 7 3

While the built-in HTTP module provides basic functionality, it lacks support for session and cookie management. Express.js serves as a higher-level framework that builds upon the HTTP module, offering enhanced features including session handling and improved usability. Think of Express as a server-side framework similar to IIS.

To begin using Express.js, first install the package using npm:

npm install express

Then create an application instance:

const express = require('express');
const application = express();

Express Configuration Settings

Express offers various configuration options that control server behavior. These settings define the environment and how Express handles JSON parsing, routing, and view rendering.

The express object provides methods for configuration:

  • set(setting, value) - Sets application configuration values
  • enable(setting) - Enables a specific setting
  • disable(setting) - Disables a specific setting
  • get(setting) - Retrieves a configuration value

Key configuration options include:

  • env: Environment mode (development, testing, production) - defaults to process.env.NODE_ENV
  • trust_proxy: Enables/disables proxy support - defaults to disabled
  • jsonp callback name: Default callback name for JSONP requests - defaults to ?callback=
  • case sensitive routing: Enables/disables case-sensitive routing - defaults to disabled
  • strict routing: Enables/disables strict route matching - defaults to disabled
  • view cache: Enables/disables template compilation caching - defaults to disabled
  • view engine: Default template engine extension for views
  • views: Directory path for view templates - defaults to ./views

Starting the Express Server

Use app.listen(port) to bind the underlying HTTP connection to a specified port and start listening. This creates the same type of connection as calling listen() on a server object created with the http library.

const express = require('express');
const http = require('http');
const application = express();

http.createServer(application).listen(8080);

application.get('/', (request, response) => {
    response.send('Hello World');
});

If you encounter a module not found error, install Express in your project directory:

npm install express

Routing in Express

Basic Routing Implementation

Routing maps HTTP requests to specific handler functions based on URL paths. Similar to .NET MVC routing, Express uses method signatures like:

application.<method>(path, [middleware, ...], callback)

Where method can be get, post, put, delete, etc., and middleware functions execute before the main callback.

Express also provides app.all() which executes for all HTTP methods on a specific path. It can use wildcard characters (*) for pattern matching, useful for logging or special request handling.

Route Parameter Handling

Route parameters allow dynamic URL segments. Express supports several parameter types:

  1. Query strings: URL parameters appended after ?key=value&key2=value2
  2. POST data: Requires middleware like body-parser
  3. Regular expressions: Pattern matching routes
  4. Named parameters: Defined parameters in URL patterns

Example implementation:

const express = require('express');
const url = require('url');
const application = express();

application.listen(8080);

application.get('/', (request, response) => {
  response.send("Home Page");
});

application.get('/search', (request, response) => {
  const url_parts = url.parse(request.url, true);
  const query = url_parts.query; 
  const result = 'Searching: Author: ' + query.author + 
                  ' Title: ' + query.title;
  console.log('\nQuery URL: ' + request.originalUrl);  
  console.log(result);
  response.send(result);
});

application.get(/^\/book\/(\w+)\:(\w+)?$/, (request, response) => {
  const result = 'Book: Chapter: ' + request.params[0] + 
              ' Page: ' + request.params[1];
  console.log('\nRegex URL: ' + request.originalUrl);
  console.log(result);
  response.send(result);
});

application.get('/user/:userId', (request, response) => {
  const result = 'User: ' + request.param('userId');
  console.log('\nParam URL: ' + request.originalUrl);
  console.log(result);
  response.send(result);
});

application.param('userId', (request, response, next, value) => {
  console.log("\nReceived request with userId: " + value);
  next();
});

When accessing these URLs in a browser:

Sample output:

Query URL: /search
Searching: Author: Brad Title: Node

Regex URL: /book/12:15
Book: Chapter: 12 Page: 15

Request received with userId: 4983

Param URL: /user/4983
User: 4983

For multiple parameters example:

const express = require('express');
const application = express();

application.listen(8080);

application.get('/user/:userId/pwd/:password', (request, response) => {
  const result = 'User: ' + request.param('userId');
  console.log('\nParam URL: ' + request.originalUrl);
  console.log(result);
  response.send(result);
});

application.param('userId', (request, response, next, value) => {
  console.log("\nReceived request with userId: " + value);
  next();
});

application.param('password', (request, response, next, value) => {
  console.log("\nReceived request with password: " + value);
  next();
});

Accessing http://127.0.0.1:8080/user/4983/pwd/123456 produces:

Request received with userId: 4983
Request received with password: 123456
Param URL: /user/4983/pwd/123456
User: 4983

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.