Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Implementing CRUD Endpoints | Building RESTful APIs
Express.js Essentials for Backend Development

Implementing CRUD Endpoints

Swipe um das Menü anzuzeigen

Implementing CRUD Endpoints

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations most APIs perform when working with data.

In Express.js, each CRUD operation is usually connected to a specific HTTP method.

Basic CRUD Example

The following example uses a simple in-memory array instead of a database. This keeps the focus on how Express.js endpoints work.

const express = require('express');

const app = express();

app.use(express.json());

let users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

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

app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name
  };

  users.push(newUser);

  res.status(201).json(newUser);
});

app.put('/users/:id', (req, res) => {
  const user = users.find(user => user.id === Number(req.params.id));

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  user.name = req.body.name;

  res.json(user);
});

app.delete('/users/:id', (req, res) => {
  users = users.filter(user => user.id !== Number(req.params.id));

  res.json({ message: 'User deleted' });
});

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

How It Works

  • The GET /users endpoint returns all users;
  • The POST /users endpoint reads data from req.body, creates a new user, and returns it with the 201 status code;
  • The PUT /users/:id endpoint uses req.params.id to find a user and update the user's name;
  • The DELETE /users/:id endpoint removes a user from the array and returns a confirmation message;
  • The express.json() middleware is important because it allows Express.js to read JSON data from the request body.
War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 4. Kapitel 2
some-alt