Open In App

Getting Started with Express JS

Express JS is a versatile, minimalist web framework for NodeJS that simplifies the development of back-end applications and APIs for web and mobile applications. Its flexibility and powerful features enable you to create robust and scalable web projects with minimal code, making it a popular choice among developers. Express is released as free and open-source software under the MIT License.

Prerequisites:

Installing Express JS:

Step 1: Create a project directory:

mkdir express-app
cd express-app

Step 2: Initialize a package.json file:

npm init -y 

Step 3: Install Express:

npm install express

Running a simple web server in Express JS:

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

// Use environment variable or default to port 3000
const port = process.env.PORT || 3000; 


app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Adding Routes for Handling request in Express JS:

Now, when you refresh your browser, you should see "Hello from my Express app!" displayed.

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

// Use environment variable or default to port 3000
const port = process.env.PORT || 3000; 

app.get('/', (req, res) => {
  // Code to handle GET requests to the root path ('/')
  res.send('Hello from my Express app!');
});

app.post('/users', (req, res) => {
  // Code to handle POST requests to the '/users' path
  // (e.g., for creating a new user)
  res.send('User creation successful!');
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Adding Parameters to Routes in Express JS:

You can capture dynamic values from URLs using parameters:

Navigate to http://localhost:3000/users/<id> (or the port you specified). You should see "User with ID: <Id you mentioned in the URL >" is displayed.

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

const port = process.env.PORT || 3000; // Use environment variable or default to port 3000

app.get('/users/:id', (req, res) => {
  const userId = req.params.id; // Access the parameter value
  res.send(`User with ID: ${userId}`);
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Modularizing Routes with Express Router:

As your application grows, managing routes in a single file can become cumbersome. Express Router allows you to create modular route handlers:

Create a separate file for routes (e.g., routes.js):

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

router.get('/', (req, res) => {
    res.send('Hello from Express routes!');
});

app.get('/users/:id', (req, res) => {
    const userId = req.params.id; // Access the parameter value
    res.send(`User with ID: ${userId} from routes`);
});

module.exports = router;

Importing and using the router in your main app (app.js):

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

// Use environment variable or default to port 3000
const port = process.env.PORT || 3000;

// Import the router
const routes = require('./routes');

// Use the router for all paths starting with '/'
app.use('/', routes);


app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});

Adding Middleware for Processing Requests in Express JS:

Middleware are functions that have access to incoming requests and outgoing responses in your Express application. They allow you to perform common tasks across multiple routes or the entire application, such as logging, authentication, and error handling.

Middleware is registered using the app.use() method. The order of middleware execution matters: they are called in the order they are registered.

Here's an example of a middleware function that logs incoming requests:

Middleware can not only log requests but also modify them before they reach the route handler. For example, a middleware can be used to parse incoming JSON data:

app.use(express.json()); // Parse incoming JSON requests automatically
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Pass control to the next middleware or route handler
});

Adding Error Handling Middleware in Express JS:

Error Handling is crucial for a robust application. Express provides a way to catch errors thrown in your application code or middleware. Here's an example of error handling middleware:

app.use((err, req, res, next) => {
  console.error(err.stack); // Log the error for debugging
  res.status(500).send('Internal Server Error'); // Send a generic error response
});

This middleware is a catch-all for any errors that haven't been handled by specific route handlers. It logs the error and sends a generic error response to the client.

Place error handling middleware at the bottom of your app.use() chain, after all other middleware and route handlers, so it catches unhandled errors. Consider providing more specific error messages for different error types in a production environment.

By implementing middleware effectively, you can streamline common tasks, improve the maintainability of your code, and create a more robust and user-friendly web application.

Article Tags :