๐Ÿ’› Getting Started with Express.js

๐Ÿ’› Getting Started with Express.js

ยท

3 min read

๐Ÿ’› What is Express.js?

Express.js, or simply Express, is a back end web application framework for building RESTful APIs with Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs.

๐Ÿ’› Getting Started with Express.js

To get started with Express.js, you'll need to have Node.js and npm (Node Package Manager) installed on your machine. Once you have Node.js installed, you can create a new Express.js project using the following steps:

  1. Create a new directory for your project. Then navigate to the newly created directory:

     mkdir my-express-app
     cd my-express-app
    
  2. Initialize a new Node.js project using npm:

     npm init -y
    
  3. Install Express.js as a dependency:

     npm install express
    
  4. Create a new JavaScript file (e.g., app.js) to write your Express.js application code.

  5. Write your Express.js application code in app.js, including defining routes, middleware, and other functionalities.

  6. Start your Express.js server:

     const express = require('express');
     const app = express();
    
     // Define routes and middleware here
    
     const PORT = process.env.PORT || 3000;
     app.listen(PORT, () => {
       console.log(`Server is running on port ${PORT}`);
     });
    

๐Ÿ’› Key Features of Express.js

  1. Routing: Express simplifies the routing process, making it easy to define application endpoints and handle various HTTP requests. Let's take a look at a basic example:
// Import Express.js
const express = require('express');
// Initialize an instance of Express.js
const app = express();

// Define a route for the homepage
app.get('/', (req, res) => {
  res.send('Welcome to Express!');
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
  1. Middleware: Middleware functions play a crucial role in Express.js applications. They can intercept incoming requests, perform tasks, and modify the request and response objects. Here's an example of a simple middleware function:
// Middleware function
const logger = (req, res, next) => {
  console.log(`Request URL: ${req.url}`);
  next();
};

// Attach middleware to the application
app.use(logger);
  1. Template Engines: While Express.js itself does not include a template engine, it integrates with popular engines like Pug, EJS, and Handlebars. These template engines allow for dynamic generation of HTML content. Here's an example using the handlebars template engine:
// Set the view engine to handlebars
app.set('view engine', 'handlebars');

// Render a dynamic view
app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.render('user', { userId });
});
  1. Error Handling: Express provides robust mechanisms for handling errors that occur during the execution of middleware or route handlers. Error handling middleware can be defined to catch and process errors gracefully.

  2. Static File Serving: Express makes serving static files such as HTML, images, CSS, and JavaScript files a breeze with its built-in middleware express.static.

     // Serve static files from the 'public' directory
     app.use(express.static('public'));
    

๐Ÿ’› Building a Simple Express.js Application

Let's put theory into practice by building a simple Express.js application. We'll create a basic server that serves a static HTML file and handles API requests.

// Import Express.js
const express = require('express');
// Initialize an instance of Express.js
const app = express();

// Serve static files from the public directory
app.use(express.static('public'));

// Define API endpoints
app.get('/api/users', (req, res) => {
  const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Charlie' }
  ];
  res.json(users);
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

๐Ÿ’› Conclusion

In conclusion, Express.js is a powerful web framework for Node.js that simplifies the process of building web applications and APIs. By understanding the fundamentals of Express.js and leveraging its capabilities, developers can streamline the development process and create high-performance web applications.

ย