Codeworx Logo

Basic CRUD Operations in Express.js: A Step-by-Step Tutorial

Faizaan

Faizaan Shaikh

Last updated:


Basic CRUD Operations in Express.js: A Step-by-Step Tutorial

CRUD operations (Create, Read, Update, Delete) are fundamental to web development, enabling interaction with data in web applications. In this tutorial, we'll explore how to implement basic CRUD operations using Express.js, a minimalist web framework for Node.js.


Introduction

Express.js is a flexible, lightweight web application framework for Node.js that provides robust features for web and mobile applications. It simplifies the development process by offering a suite of features for building web and mobile apps, making it an ideal choice for building RESTful APIs and handling CRUD operations.

In this tutorial, we'll build a simple Express.js application to perform CRUD operations on a list of users.

Setting Up Project

Before we start coding, we need to set up a basic Node.js project and install the necessary dependencies.

Step 1: Initialize a New Node.js Project

First, create a new directory for your project and navigate into it:

mkdir express-crud
cd express-crud

Then, initialize a new Node.js project:

npm init -y

This command will create a `package.json` file with default settings.

Step 2: Install Dependencies

We'll need to install Express.js and some other useful middleware:

npm install express nodemon
  • Express: The web framework we'll use to create our server.

  • Nodemon: A tool that automatically restarts the server whenever code changes, helpful during development.

Creating the Express Server

Now that we've set up our project, let's create the basic Express server.

Step 1: Create the Server File

Create a new file called `index.js` in your project directory:

touch index.js

Step 2: Set Up the Express Application

Open `index.js` in your preferred text editor and add the following code:

const express = require('express');

const app = express();
const PORT = process.env.PORT || 3000;


// Middleware
app.use(express.json());


// Basic route
app.get('/', (req, res) => {
  res.send('Welcome to the Express CRUD API!');
});


app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

This code sets up a basic Express server that listens on port 3000 and includes a single route that returns a welcome message.

Step 3: Run the Server

Start the server using `nodemon`:

npx nodemon index.js

Visit http://localhost:3000 in your browser, and you should see the welcome message.

Setting Up Routes for CRUD Operations

Now, let’s add routes to handle the CRUD operations for our user data.

Step 1: Create In-Memory Data Storage

For simplicity, we'll use an array to store our user data. Add the following code above your route definitions in `index.js`:

Step 2: Create Operation

To add new users, we'll create a POST route.

// Create a new user
app.post("/users", (req, res) => {
  const user = req.body;
  users.push(user);
  res.status(201).json({
    message: `User with the name ${user.name} added to the database.`,
  });
});

This route accepts a user object in the request body and adds it to the "users" array.

Step 3: Read Operation

To retrieve users, we'll create a GET route.

// Get all users
app.get("/users", (req, res) => {
  if (!users.length) {
    return res.status(404).json({
      message: "No user data available",
      users,
    });
  }
  res.json({
    message: "Successfully fetched users",
    users,
  });
});


// Get a specific user
app.get("/users/:blogId", (req, res) => {
  const { blogId } = req.params;
  console.log(blogId);
  const user = users.find((user) => user.blogId === parseInt(blogId));
  if (user) {
    res.json({
      message: "User available",
      user,
    });
  } else {
    return res.status(404).json({
      message: `Couldn't find User with 'blogId'=${blogId}`,
      user,
    });
  }
});

These routes will return all users or a specific user by ID.

Step 4: Update Operation

To update an existing user, we’ll create a PUT route.

// Update a user
app.put("/users/:blogId", (req, res) => {
  const { blogId } = req.params;
  const { name, email } = req.body;
  const user = users.find((user) => user.blogId === parseInt(blogId));


  if (user) {
    user.name = name;
    user.email = email;
    res.status(200).json({
      message: `User with the blogId ${blogId} has been updated`,
      user,
    });
  } else {
    res.status(404).json({ message: `Couldn't find User with 'blogId'=${blogId}` });
  }
});

This route will update the user’s name and email based on the ID provided.

Step 5: Delete Operation

Finally, we'll add a DELETE route to remove a user.

// Delete a user
app.delete("/users/:blogId", (req, res) => {
  const { blogId } = req.params;
  users = users.filter((user) => user.blogId !== parseInt(blogId));
  res.status(200).json({
    message: `User with the blogId ${blogId} deleted from the database.`,
  });
});

This route filters out the user with the specified ID from the `users` array.

Testing the CRUD Operations

You can test these CRUD operations using tools like Postman or VsCode Extension called Thunder client . Below are examples of how to use each operation:

1. Create a User (POST /users)

  • URL: http://localhost:3000/users

  • Method: POST

  • Body:

{
  "blogId": 1,
  "name": "John Doe",
  "email": "johndoe@example.com"
}

2. Get all Users (GET/users)

  • URL: http://localhost:3000/users

  • Method: GET

3.Get a User by ID (GET/users/)

  • URL: http://localhost:3000/users/1

  • Method: GET

4. Update a User (PUT/users/)

  • URL: http://localhost:3000/users/1

  • Method: PUT

  • Body:

{
  "name": "Jane Doe",
  "email": "janedoe@example.com"
}

5.Delete a User (DELET/users/)

  • URL: http://localhost:3000/users/1

  • Method: DELETE

Conclusion

In this tutorial, we’ve built a basic Express.js application that handles CRUD operations for user data. You can extend this application by connecting it to a database like MongoDB or MySQL, adding authentication, and more. Express.js provides a solid foundation for building robust and scalable web applications. Keep experimenting and adding features to deepen your understanding of Express.js and RESTful APIs.

Related Blogs

CodeWorx

© Copyright 2024 - Codeworx