Dies ist eine alte Version des Dokuments!
LU11c - CRUD Server and Postman
Learning Objectives
- How to connect the server to the db
- How to fetch data from the db and display it in POSTMAN
- How to perform the CRUD operations on the server
- How to perform the CRUD operations by using PoSTMAN
Sources
Introduction
At last chapter of our database journey we want to perform all CRUD operations within the server AND the client (POSTMAN).
Fetching list of data
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 }); });
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]); } }); });