Language: EN

como-usar-expressjs-con-nodejs

How to Use Express.js with Node.js

Express.js is a web development framework that simplifies the creation of web applications and APIs in Node.js. Without a doubt, it is the most popular and widely used framework for creating web servers.

Express.js offers a series of features such as routing, middleware, and handling HTTP requests and responses. Additionally, it is a stable, proven, and widely used framework.

However, it is a framework that has been around for quite some time. Therefore, numerous alternatives have emerged, including the native library node:http, which has improved greatly over time.

Nevertheless, it remains one of the best and most used alternatives. It has a large community and available documentation. Therefore, it is interesting that you at least know and know how to use it.

How to use Express.js

Installation of Express.js

To begin, we need to install Express.js in our project. We can do this using npm (Node Package Manager) with the following command in the terminal:

npm install express

Once installed, we can import Express.js into our code to start creating our web server.

const express = require('express');
const app = express();
const PORT = 3000; // Port on which the server will listen

// here we would define the routes
// see below

// Start the server
app.listen(PORT, () => {
  console.log(`Express server listening on port ${PORT}`);
});

That’s how easy it is to create a web server with Express.js.

Creating routes with Express.js

One of the most outstanding features of Express.js is its routing system. It allows us to define routes to handle different types of HTTP requests, such as GET, POST, PUT, and DELETE. Next, we will see how to create and handle routes in Express.js.

To define a route in Express.js, we use the routing methods such as app.get(), app.post(), app.put(), app.delete(). These methods take the URL of the route as the first argument and a controller function that will be executed when a request is made to that route.

Example of a GET Route

app.get('/', (req, res) => {
  res.send('Hello, world from Express.js!');
});

In this example, we are defining a GET route at the root route ('/') that responds with the message “Hello, world from Express.js!“.

Example of a POST Route

app.post('/users', (req, res) => {
  res.send('User information received and processed');
});

In this POST route, we respond with a message indicating that the user information has been received and processed.

Example of a Dynamic Route

In this dynamic route, we capture any value after /users/ using req.params. Then we respond with the requested user’s ID.

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

Middleware in Express.js

Express.js also offers middleware, functions that run before reaching the final route. This allows us to perform actions such as validating data, handling errors, or authenticating users before reaching the route handler.

Example of Request Logging Middleware

In this example, every time a request comes to the server, we log the URL of the request in the console before continuing with the next function in the middleware chain.

app.use((req, res, next) => {
  console.log(`Request received at: ${req.url}`);
  next();
});

Example of Error Handling Middleware

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong');
});

Here we have an error handling middleware that captures any error that occurs during the processing of a request and sends a 500 error response along with a generic error message.

Complete Example of an Express.js Application

Next, we will see a complete example of an Express.js application that uses routing and middleware:

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

// Request logging middleware
app.use((req, res, next) => {
  console.log(`Request received at: ${req.url}`);
  next();
});

// GET route at the root
app.get('/', (req, res) => {
  res.send('Hello, world from Express.js!');
});

// POST route for users
app.post('/users', (req, res) => {
  res.send('User information received and processed');
});

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

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong');
});

// Start the server
app.listen(PORT, () => {
  console.log(`Express server listening on port ${PORT}`);
});

This example shows how to create a basic web server with Express.js, define routes to handle different types of HTTP requests, and use middleware to perform additional tasks such as request logging and error handling.