"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Express.js Essentials

Express.js Essentials

Published on 2024-11-07
Browse:347

Express.js Essentials

This article focuses on essential things to know Express.js, a key part of building backend applications with Node.js. I'll dive into routing, CRUD operations, response methods, and middleware functions, all of which play a critical role in building robust web applications.

Concept Highlights:

  1. Route Methods and CRUD
  2. Routing Parameters
  3. Route Handlers
  4. Response Methods
  5. Built-in Middleware Functions

1. Route Methods and CRUD

In Express.js, route methods define how your application responds to different HTTP requests (e.g., GET, POST, PUT, DELETE) for specific routes. These methods are used to implement CRUD (Create, Read, Update, Delete) operations in your application.

Basic CRUD example: In this example, each route responds to a different CRUD operation based on the HTTP method used.

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

// Create - POST
app.post('/users', (req, res) => {
  res.send('User created');
}); 

// Read - GET
app.get('/users', (req, res) => {
  res.send('Here is the user'); 
}); 

// Update - PUT
app.put('/users/:id', (req, res) => {
  res.send('User with ID ${req.params.id} updated'); 
});

// Delete - DELETE
app.delete('/users//:id', (req, res) => {
  res.send('User with ID ${req.params.id} deleted');
}):

app.listen(3000, () => 
  console.log('Server running on port 3000')
);

2. Routing Parameters

Routing parameters allow you to capture specific parts of the request URL and use them within your route handlers. For instance, you can extract an ID from the URL and use it to perform an action related to that ID.

e.g.) In this example, :id is a dynamic parameter, which will be extracted and used in the response. If this dynamic parameter is 123, a request to /users/123 will return "Fetching user with ID: 123."

app.get('/users/:id', (req, res) => {
  const userId = req.params.id; 
  res.send(`Fetching user with ID: ${userId}`);
});

3. Route Handlers

Route handlers define how your server handles HTTP requests. You can define multiple middleware functions within a single route, allowing for cleaner and modular code.

Example with multiple handlers: In this example, the first middleware logs a message, and the second middleware sends the response.

app.get('/users', (req, res, next) => {
  console.log('First middleware');
  next(); // call the next handler in the stack
}, (req, res) => {
  res.send('User list'); 
});

4. Response Methods

Express.js provides several methods for sending responses to the client. Let's explore some commonly used response methods.

a) .json() sends a JSON response.

app.get('/data', (req, res) => {
  res.json({ message: 'Hello, JSON' });
});

b) .send() sends a response of various types (text, HTML, buffer, etc.).

app.get('/text', (req, res) => {
  res.send('Sending text');
});

c) .download() sends a file as an attachment, prompting the user to download it.


app.get('/download', (re




Release Statement This article is reproduced at: https://dev.to/ryoichihomma/expressjs-essentials-5e83?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3