Getting Started with Express.js: Learning the Basics with Examples

learn express.js

Sharing is caring!

94 Views -

Express.js is a popular web application framework for Node.js that simplifies the process of building web applications. Whether you are a beginner or an experienced developer, learning Express.js can greatly enhance your ability to create scalable and efficient web applications. In this blog post, we will guide you through the basics of Express.js and provide examples to help you understand its core concepts in 2023.

  • Setting Up a Basic Express.js Server

To begin, let’s create a basic Express.js server that listens for incoming HTTP requests and responds with a simple message. Here’s an example

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

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

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

In this example, we import the Express module, create an instance of the Express application, define a route for the root URL (“/”), and specify a callback function to handle the request and send a response.

  • Routing and Handling HTTP Requests

Express.js provides a powerful routing mechanism to handle different HTTP requests. Let’s explore a few examples

app.get('/about', (req, res) => {
  res.send('About Us');
});

app.post('/users', (req, res) => {
  // Create a new user
});

app.put('/users/:id', (req, res) => {
  // Update a user with the specified ID
});

app.delete('/users/:id', (req, res) => {
  // Delete a user with the specified ID
});

In these examples, we define routes for different HTTP methods (GET, POST, PUT, DELETE) along with their respective URLs. The callback functions can be used to handle the requests and perform the necessary operations.

  • Body Parser: Handling Request Data

The Body Parser module simplifies the process of parsing and accessing request data, such as form submissions or JSON payloads. Here’s an example of how to use Body Parser to parse JSON data

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());

app.post('/users', (req, res) => {
  const user = req.body;
  // Process the user data
  res.json(user);
});
  • Accessing Request Parameters and Query Strings

Express.js allows you to access request parameters and query strings sent by clients. Here’s an example

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

app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Search query: ${query}`);
});

In the first, we define a route with a parameter “:id” and access it using req.params.id. In the second, we retrieve the value of the “q” query parameter using req.query.q.

  • Serving Static Files

Express.js simplifies the process of serving static files such as HTML, CSS, and client-side JavaScript. Here’s an example

app.use(express.static('public'));

In this example, we create a “public” directory and place our static files inside it. Express.js automatically serves these files when the corresponding URLs are accessed.

  • Cookie Parser: Handling Cookies

The Cookie Parser module allows you to parse and handle cookies sent by the client. Here’s an example of how to use Cookie Parser to access cookies in Express.js

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

app.use(cookieParser());

app.get('/visited', (req, res) => {
  const visitedBefore = req.cookies.visited;
  if (visitedBefore) {
    res.send('Welcome back!');
  } else {
    res.cookie('visited', 'true');
    res.send('Welcome for the first time!');
  }
});
  • Express-Session: Managing User Sessions

Express-Session is a module that enables session management in Express.js applications. It provides a way to store user data between requests, such as authentication status or user preferences. Here’s a simple example

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

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
}));

app.get('/dashboard', (req, res) => {
  if (req.session.isAuthenticated) {
    res.send('Welcome to the dashboard!');
  } else {
    res.redirect('/login');
  }
});
  • Express-Validator: Request Data Validation

The Express-Validator module helps validate and sanitize user input to ensure data integrity and security. Here’s a basic example of using Express-Validator for form validation

const express = require('express');
const { check, validationResult } = require('express-validator');
const app = express();

app.post('/register', [
  check('username').isLength({ min: 3 }),
  check('email').isEmail(),
  check('password').isLength({ min: 6 }),
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  // Process the registration data
  res.send('Registration successful!');
});
  • Error Handling

Express.js provides error-handling mechanisms to handle runtime errors and exceptions gracefully. Here’s an example of a basic error handler.

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

In this example, we define an error handler middleware function that takes four parameters. If an error occurs, it will be passed to this function for handling.
Conclusion

Express.js is a powerful and flexible framework for building web applications in Node.js. In this blog post, we covered the basics of Express.js, including setting up a server, routing and handling HTTP requests, accessing request parameters and query strings, serving static files, and error handling. Armed with this knowledge and the provided examples, you can now start exploring and building your own Express.js applications in 2023.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments