Express: User Management
Develop a basic Express.js application that simulates a simple user management system. The application should define a /users route that allows interaction through different HTTP methods. Begin by initializing an in-memory array to hold user objects, where each object includes three properties: id, name, and email.
Implement functionality to return all users using the
GETmethod on/users.Allow new users to be added via the
POSTmethod to the same route. Each new user should receive a unique ID that increments sequentially.Implement the
DELETEmethod on/users/:idto remove a specific user by ID.Ensure that the application uses
express.json()middleware to parse incoming JSON request bodies and returns appropriate JSON responses for each action. Include basic error handling to display a clear message when attempting to delete a user that does not exist.
app.js
import express from 'express';
const app = express();
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// In-memory data store
let users = [
{ id: 1, name: 'Alice Johnson', email: 'alice@example.com' },
{ id: 2, name: 'Bob Smith', email: 'bob@example.com' }
];
// --- Routes ---
// GET /users - Retrieve all users
app.get('/users', (req, res) => {
res.json(users);
});
// POST /users - Add a new user
let nextId = 3;
app.post('/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email){
return res.status(400).json({message: "Both needed"});
}
const newUser = {
id: nextId++,
name,
email };
users.push(newUser);
res.status(201).json(newUser);
});
// DELETE /users/:id - Remove a user by ID
app.delete('/users/:id', (req, res) => {
const userId = parseInt(req.params.id, 10);
const userIndex = users.findIndex(user => user.id === userId);
if (userIndex === -1) {
return res.status(404).json({ message: 'User not found' });
}
users.splice(userIndex, 1);
res.json({ message: 'User deleted successfully' });
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});Run and Test
npm init -y
npm install expressEnsure package.json includes "type": "module".
node app.jsTest the API (using curl):
Get all users:
curl http://localhost:3000/usersAdd a new user:
curl -X POST -H "Content-Type: application/json" -d '{"name":"Charlie Brown","email":"charlie@example.com"}' http://localhost:3000/usersDelete a user:
curl -X DELETE http://localhost:3000/users/1Attempt to delete a non-existent user:
curl -X DELETE http://localhost:3000/users/99
Test API with Postman
Get all users (GET)
Open Postman and create a new request.
Set the method to GET.
Enter the URL:
http://localhost:3000/users.Click Send. You will see the array of users in the response body.
Add a new user (POST)
Create a new request.
Set the method to POST.
Enter the URL:
http://localhost:3000/users.Go to the Body tab, select raw, and choose JSON from the dropdown.
In the text area, enter the new user's data:
{
"name": "Charlie Brown",
"email": "charlie@example.com"
}- Click Send. You will get the newly created user object back with its ID.
Delete a user (DELETE)
Create a new request.
Set the method to DELETE.
Enter the URL for a specific user, for example:
http://localhost:3000/users/1.Click Send. You will receive a success message.
Attempt to delete a non-existent user (DELETE)
In the previous
DELETErequest, change the URL to an ID that doesn't exist, like:http://localhost:3000/users/99.Click Send. The API will correctly return a 404 Not Found status with the message
"User not found".
