Express.js

 Express.js is a popular web application framework for Node.js. It simplifies the process of building web applications and APIs by providing a robust set of features and utilities. Express.js is minimalistic and unopinionated, allowing developers to structure their applications according to their preferences. Here's an explanation of Express.js along with an example:

Explanation of Express.js:

  1. Routing: Express.js provides a simple and intuitive routing mechanism that allows you to define routes for handling HTTP requests. Routes can be defined for various HTTP methods (GET, POST, PUT, DELETE, etc.) and URL patterns.

  2. Middleware: Middleware functions are functions that have access to the request and response objects and can modify them or perform additional tasks. Express.js allows you to use middleware to perform tasks such as logging, authentication, and error handling.

  3. Template Engines: Express.js supports various template engines, such as Pug, EJS, and Handlebars, which allow you to dynamically generate HTML content based on data.

  4. Static Files: You can serve static files, such as CSS, JavaScript, and images, using Express.js by specifying a directory to serve static files from.

  5. Error Handling: Express.js provides built-in error handling mechanisms that allow you to handle errors gracefully and provide meaningful error messages to users.

Example of a Simple Express.js Application:

Let's create a simple Express.js application that serves a static HTML file and handles a GET request:

  1. Install Express.js:

  2. npm install express

Create an app.js file:
// Import the Express.js module const express = require('express'); // Create an instance of the Express application const app = express(); // Define a route handler for the root URL app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); // Start the server and listen on port 3000 app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });

Create an index.html file:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Express.js Example</title> </head> <body> <h1>Hello, Express.js!</h1> </body> </html>

Run the Application:
node app.js

  1. Open your web browser and navigate to http://localhost:3000. You should see the message "Hello, Express.js!" displayed on the page.

This example demonstrates a basic Express.js application that serves a static HTML file when a GET request is made to the root URL (/). Express.js simplifies the process of creating web applications and APIs by providing a clean and intuitive interface for handling HTTP requests and responses.

Let's create a simple project using Express.js to build a basic API for managing a list of tasks. In this project, we'll set up routes to perform CRUD (Create, Read, Update, Delete) operations on tasks.

Project Structure:

project/
├── app.js
└── tasks.js

app.js - Main Application File:


const express = require('express');
const tasksRouter = require('./tasks');

const app = express();
const PORT = 3000;

app.use(express.json());
app.use('/tasks', tasksRouter);

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

tasks.js - Task Routes File:


const express = require('express');
const router = express.Router();

let tasks = [
  { id: 1, title: 'Task 1', completed: false },
  { id: 2, title: 'Task 2', completed: true }
];

// Get all tasks
router.get('/', (req, res) => {
  res.json(tasks);
});

// Get a single task
router.get('/:id', (req, res) => {
  const taskId = parseInt(req.params.id);
  const task = tasks.find(task => task.id === taskId);
  if (task) {
    res.json(task);
  } else {
    res.status(404).send('Task not found');
  }
});

// Create a new task
router.post('/', (req, res) => {
  const { title, completed } = req.body;
  const newTask = { id: tasks.length + 1, title, completed };
  tasks.push(newTask);
  res.status(201).json(newTask);
});

// Update a task
router.put('/:id', (req, res) => {
  const taskId = parseInt(req.params.id);
  const { title, completed } = req.body;
  const taskIndex = tasks.findIndex(task => task.id === taskId);
  if (taskIndex !== -1) {
    tasks[taskIndex] = { ...tasks[taskIndex], title, completed };
    res.json(tasks[taskIndex]);
  } else {
    res.status(404).send('Task not found');
  }
});

// Delete a task
router.delete('/:id', (req, res) => {
  const taskId = parseInt(req.params.id);
  tasks = tasks.filter(task => task.id !== taskId);
  res.send('Task deleted successfully');
});

module.exports = router;

Usage:

  1. Install Express.js:


  2. npm install express


  3. Run the application:


  4. node app.js


Testing the API Endpoints:

  • GET /tasks: Retrieves all tasks.
  • GET /tasks/:id: Retrieves a single task by ID.
  • POST /tasks: Creates a new task.
  • PUT /tasks/:id: Updates an existing task by ID.
  • DELETE /tasks/:id: Deletes a task by ID.

You can use tools like Postman or curl commands to test the API endpoints.

This example demonstrates a simple project using Express.js to create a RESTful API for managing tasks. You can extend this project by adding more features such as authentication, validation, and database integration for persistent storage.


Post a Comment

0 Comments