Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Implementing CRUD Endpoints | Building RESTful APIs
Express.js Essentials for Backend Development

Implementing CRUD Endpoints

Свайпніть щоб показати меню

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.
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 2

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 4. Розділ 2
some-alt