Loading...
Loading...

Node.js CRUD Operations

In this tutorial, you'll learn how to build a simple Node.js application to perform CRUD (Create, Read, Update, Delete) operations using Express and a mock data array.

1. Setting Up the Project

Start by setting up a new Node.js project:

mkdir crud-app
cd crud-app
npm init -y
npm install express body-parser

This initializes a new project, installs Express, and the body-parser middleware to handle JSON requests.

2. Create the CRUD API

Now, create `app.js` to define routes for each CRUD operation:

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

// Mock data
let users = [{ id: 1, name: 'John Doe' }];

// Create user
app.post('/users', (req, res) => {
    const newUser = req.body;
    newUser.id = users.length + 1;
    users.push(newUser);
    res.status(201).json(newUser);
});

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

// Update user
app.put('/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (user) {
        user.name = req.body.name;
        res.json(user);
    } else {
        res.status(404).send('User not found');
    }
});

// Delete user
app.delete('/users/:id', (req, res) => {
    const index = users.findIndex(u => u.id === parseInt(req.params.id));
    if (index !== -1) {
        users.splice(index, 1);
        res.status(204).send();
    } else {
        res.status(404).send('User not found');
    }
});

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

This code defines routes for creating, reading, updating, and deleting users. It uses mock data for demonstration.

3. Running the Server

Run the application with:

node app.js

After starting the server, you can test CRUD operations using Postman or by making HTTP requests directly.

4. Conclusion

You've successfully built a simple CRUD API with Node.js and Express. You can expand this by integrating a real database and adding more complex logic to your API.

0 Interaction
369 Views
Views
22 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home