como-usar-expressjs-con-nodejs

How to Use Express.js with Node.js

  • 4 min

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, HTTP request and response management. Furthermore, it is a stable, proven, and widely used framework.

However, it is a framework that has been around for quite some time. Consequently, numerous alternatives have emerged, including the native node:http library itself, which has improved a lot 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 about it and know how to use it.

How to use Express.js

Installing 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}`);
});
Copied!

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

Creating Routes with Express.js

One of the most notable features of Express.js is its routing system. It allows you 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 routing methods like app.get(), app.post(), app.put(), app.delete(). These methods take as their first argument the URL of the route and a controller function that will be executed when a request is made to that route.

Middleware in Express.js

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

Complete Express.js Application Example

Next, let’s 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}`);
});
Copied!

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.

Download the code

All the code from this post is available for download on Github github-full