Page cover

Building a Basic CRUD Application with Express.js Without a Database

Creating a CRUD (Create, Read, Update, Delete) application is a fundamental skill for web developers. While databases are typically used to store and manage data in such applications, understanding how to build a basic CRUD app without a database can be an excellent learning exercise. This tutorial will walk you through creating a simple CRUD application using Express.js and in-memory storage.

Setting Up the Project

First, ensure you have Node.js and npm (Node Package Manager) installed on your system. Create a new directory for your project and navigate into it via the terminal:

mkdir express-crud-app
cd express-crud-app

Initialize a new Node.js project:

npm init -y

Install Express.js:

npm install express

Create an index.js file in your project directory. This will be the main file for our Express application.

Creating the Express Server

In index.js, start by setting up a basic Express server:

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

app.use(express.json());

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

This code sets up an Express server that listens on port 3000. The express.json() middleware is used to parse JSON bodies of incoming requests.

In-Memory Data Storage

Instead of a database, we'll use an in-memory array to store our data. Add the following array at the top of your index.js file:

let items = [];

Implementing CRUD Operations

Create (POST)

Add a route to handle creating new items:

app.post('/items', (req, res) => {
    const newItem = {
        id: items.length + 1,
        name: req.body.name,
        description: req.body.description,
    };
    items.push(newItem);
    res.status(201).json(newItem);
});

This route listens for POST requests at /items, creates a new item with a unique ID, and adds it to the items array.

Read (GET)

Add routes to read items:

// Get all items
app.get('/items', (req, res) => {
    res.json(items);
});

// Get a single item by ID
app.get('/items/:id', (req, res) => {
    const item = items.find(i => i.id === parseInt(req.params.id));
    if (!item) return res.status(404).send('Item not found');
    res.json(item);
});

These routes allow you to retrieve all items or a single item by its ID.

Update (PUT)

Add a route to update an item:

app.put('/items/:id', (req, res) => {
    const item = items.find(i => i.id === parseInt(req.params.id));
    if (!item) return res.status(404).send('Item not found');

    item.name = req.body.name;
    item.description = req.body.description;
    res.json(item);
});

This route finds an item by ID and updates its name and description.

Delete (DELETE)

Add a route to delete an item:

app.delete('/items/:id', (req, res) => {
    const itemIndex = items.findIndex(i => i.id === parseInt(req.params.id));
    if (itemIndex === -1) return res.status(404).send('Item not found');

    const deletedItem = items.splice(itemIndex, 1);
    res.json(deletedItem);
});

This route finds an item by ID and removes it from the items array.

Testing the Application

To test your CRUD operations, you can use a tool like Postman or curl.

Create an Item

curl -X POST http://localhost:3000/items -H "Content-Type: application/json" -d '{"name":"Item1", "description":"This is item 1"}'

Get All Items

curl http://localhost:3000/items

Get a Single Item

curl http://localhost:3000/items/1

Update an Item

curl -X PUT http://localhost:3000/items/1 -H "Content-Type: application/json" -d '{"name":"Updated Item", "description":"Updated description"}'

Delete an Item

curl -X DELETE http://localhost:3000/items/1

Conclusion

You've now built a simple CRUD application using Express.js without a database. This setup is great for learning and testing, but for real-world applications, integrating a database is essential for data persistence. Understanding these basic operations lays a solid foundation for more complex applications in the future. Happy coding!

Last updated