Dies ist eine alte Version des Dokuments!


LU11c - CRUD Server and Postman

  1. How to connect the server to the db
  2. How to fetch data from the db and display it in POSTMAN
  3. How to perform the CRUD operations on the server
  4. How to perform the CRUD operations by using PoSTMAN

At last chapter of our database journey we want to perform all CRUD operations within the server AND the client (POSTMAN). For reasons of efficiency we are going to start with the R = READ of CRUD.

First of all, we want to display the list of users, which are store in the table users. The following code show how to get that list from the database.

// Method to get data from the user table
app.get('/user', (req, res) => {
    const query = 'SELECT * FROM users'; // SQL query to select all rows from user table
    db.query(query, (err, results) => {
        if (err) {
            console.error('Error retrieving users:', err);
            res.status(500).send('Server error');
            return;
        }
        res.json(results); // Send the results as JSON
    });
});

 c_R_ud performance in the presentation (POSTMAN) and logic layer (Node Server)}

==== R = READ: Getting one spefific row of data ====
If we want one speficific individual to be displayed, we need to make some changes, such as filtering a user_id, as shown in the following code below.

  app.get('/user/:id', (req, res) => {
      const userId = req.params.id;
      // SQL query to fetch user by id
      const query = 'SELECT * FROM users WHERE user_id = ?';
      db.query(query, [userId], (err, results) => {
          if (err) {
              console.error('Error fetching user:', err);
              res.status(500).send('Server error');
              return;
          }
          if (results.length === 0) {
              res.status(404).send('User not found');
          } else {
              res.status(200).json(results[0]);
          }
      });
  });

{{:modul:m290:learningunits:lu09:theorie:crud_r2.png?800|c_R_ud performance in the presentation (POSTMAN) and logic layer (Node Server)}

==== Deleting on user from the table ====
// DELETE user method
app.delete('/user/:id', (req, res) => {
    const userId = req.params.id;

    const deleteQuery = 'DELETE FROM users WHERE user_id = ?';

    db.query(deleteQuery, [userId], (err, result) => {
        if (err) {
            res.status(500).send('Error deleting user');
        } else if (result.affectedRows === 0) {
            res.status(404).send('User not found');
        } else {
            res.send(`User with ID ${userId} deleted successfully`);
        }
    });
});
==== Vocabulary ====
^English ^ Deutsch ^
| ...| ...|


----
[[https://creativecommons.org/licenses/by-nc-sa/4.0/|{{https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png]] Volkan Demir

  • modul/m290/learningunits/lu09/theorie/03.1730810222.txt.gz
  • Zuletzt geändert: 2024/11/05 13:37
  • von vdemir