Deepening NodeJS Knowledge: URLs, HTTP Methods, Express Framework, and Versioning

Sushant Gaurav - Aug 21 - - Dev Community

Continuing from where we left off, let’s dive deeper into some more advanced topics in NodeJS. If you want to know the basics or you want to read the article series from starting, click here.

Parts of a URL and How URLs Work in NodeJS

Parts of a URL

URL stands for Uniform Resource Locator which is used to specify addresses on the web.

  • Components of a URL:
    1. Protocol: The method used to access the resource. (e.g., http, https, ftp)
      • Example: https://
    2. Hostname: The domain name or IP address where the resource is hosted.
      • Example: www.example.com
    3. Port: The port number where the server is listening. (default for http is 80 and for https is 443)
      • Example: :8080 (optional)
    4. Pathname: The path to the specific resource.
      • Example: /path/to/resource
    5. Query String: Key-value pairs used to pass data to the server.
      • Example: ?id=123&name=John
    6. Fragment: A reference to a section within a resource.
      • Example: #section1 (optional)

Example URL:

https://www.example.com:8080/path/to/resource?id=123&name=John#section1
Enter fullscreen mode Exit fullscreen mode

How URLs Work in NodeJS?

NodeJS provides the url module to work with URLs, making it easy to parse and construct them.

Example:

const url = require('url');

// Sample URL
const myURL = 'https://www.example.com:8080/path/to/resource?id=123&name=John#section1';

// Parsing the URL
const parsedURL = url.parse(myURL, true);

console.log(parsedURL);
Enter fullscreen mode Exit fullscreen mode

Output:

Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.example.com:8080',
  port: '8080',
  hostname: 'www.example.com',
  hash: '#section1',
  search: '?id=123&name=John',
  query: { id: '123', name: 'John' },
  pathname: '/path/to/resource',
  path: '/path/to/resource?id=123&name=John',
  href: 'https://www.example.com:8080/path/to/resource?id=123&name=John#section1'
}
Enter fullscreen mode Exit fullscreen mode

Explanation: The url.parse() function breaks down the URL into its components, making it easier to work with each part.

URL Package for NodeJS and Its Important Functions

url.parse()

It parses a URL string into an object containing properties such as protocol, hostname, pathname, query, etc.

  • Usage:
  const parsedURL = url.parse('https://www.example.com:8080/path/to/resource?id=123&name=John#section1', true);
  console.log(parsedURL.hostname); // 'www.example.com'
Enter fullscreen mode Exit fullscreen mode

url.format()

It converts a URL object back into a URL string.

  • Usage:
  const urlObject = {
      protocol: 'https',
      hostname: 'www.example.com',
      port: '8080',
      pathname: '/path/to/resource',
      query: { id: '123', name: 'John' },
  };

  const formattedURL = url.format(urlObject);
  console.log(formattedURL); // 'https://www.example.com:8080/path/to/resource?id=123&name=John'
Enter fullscreen mode Exit fullscreen mode

url.resolve()

It resolves a target URL relative to a base URL.

  • Usage:
  const base = 'https://www.example.com/home/';
  const relative = 'about';

  const resolvedURL = url.resolve(base, relative);
  console.log(resolvedURL); // 'https://www.example.com/home/about'
Enter fullscreen mode Exit fullscreen mode

Methods of HTTP

Overview of HTTP Methods

HTTP methods define the type of action to be performed on a resource. They are the foundation of RESTful web services.

  • Common HTTP Methods:
    1. GET: Retrieve data from the server.
    2. POST: Send data to the server, often to create or update resources.
    3. PUT: Update an existing resource on the server.
    4. DELETE: Remove a resource from the server.
    5. PATCH: Apply partial modifications to a resource.
    6. HEAD: Same as GET, but without the response body.
    7. OPTIONS: Describes the communication options for the target resource.

Working with HTTP Methods in NodeJS

You can handle different HTTP methods in NodeJS by checking the req.method property.

Example:

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('GET request received\n');
    } else if (req.method === 'POST') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('POST request received\n');
    } else {
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end(`${req.method} not allowed\n`);
    }
});

server.listen(3000, '127.0.0.1', () => {
    console.log('Server running at http://127.0.0.1:3000/');
});
Enter fullscreen mode Exit fullscreen mode

Output:

  • GET Request: GET request received
  • POST Request: POST request received
  • Any Other Method: {METHOD} not allowed

Express Framework

What is Express?

Express is a fast, unopinionated, minimalist web framework for NodeJS. It simplifies the process of building web applications and APIs by providing a robust set of features and middleware.

The Problem Express Solves

  • Complexity in HTTP Server Handling:
    • In vanilla NodeJS, managing routes, handling different HTTP methods, and working with middlewares can become cumbersome as the application grows.
    • Express abstracts this complexity, allowing developers to write cleaner and more maintainable code.

How Express Solves the Problem?

  • Routing: Simplifies route handling with a clean syntax.
  • Middleware: Provides a way to handle common tasks such as parsing request bodies, handling cookies, and managing sessions.
  • Error Handling: Centralized error handling mechanism.
  • Third-Party Integrations: Easy integration with various libraries and plugins for extended functionality.

Basic Example of an Express Application

Installation:

npm install express
Enter fullscreen mode Exit fullscreen mode

Code:

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

// Home route
app.get('/', (req, res) => {
    res.send('Hello, Express!');
});

// About route
app.get('/about', (req, res) => {
    res.send('About Page');
});

// Start the server
app.listen(3000, () => {
    console.log('Express server running at http://127.0.0.1:3000/');
});
Enter fullscreen mode Exit fullscreen mode

Output:

  • Navigate to http://127.0.0.1:3000/ -> Displays: "Hello, Express!"
  • Navigate to http://127.0.0.1:3000/about -> Displays: "About Page"

Working of Versioning in NodeJS

NodeJS follows SemVer, which is a versioning scheme using three numbers: MAJOR.MINOR.PATCH.

  • MAJOR: Introduces breaking changes.
  • MINOR: Adds functionality in a backward-compatible manner.
  • PATCH: Backward-compatible bug fixes.

NodeJS Version Management

NodeJS releases come in two types:

  1. LTS Releases: Recommended for most users; focus on stability and security.
  2. Current Releases: Include the latest features but may not be as stable as LTS.

Using Node Version Manager (NVM)

Node Version Manager (NVM) is a tool that allows you to install and switch between different versions of NodeJS easily.

Installation (Linux/MacOS):

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash
Enter fullscreen mode Exit fullscreen mode

Common NVM Commands:

  • Install a specific version: nvm install 14.17.0
  • Use a specific version: nvm use 14.17.0
  • List installed versions: nvm ls
  • Set default version: nvm alias default 14.17.0

Example of Version Switching

Code:

nvm install 16.0.0
nvm use 16.0.0
node -v # Outputs: v16.0.0

nvm use 14.17.0
node -v # Outputs: v14.17.0
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .