Expressjs Handling Get Post Put Delete Requests Complete Guide
Understanding the Core Concepts of Expressjs Handling GET, POST, PUT, DELETE Requests
Express.js Handling GET, POST, PUT, DELETE Requests
1. Handling GET Requests
GET requests are used to retrieve data from the server. They are non-destructive and safe, meaning they should not alter the server state. In Express.js, routes are easy to set up and manage.
Example:
const express = require('express');
const app = express();
// Route to get all users
app.get('/users', (req, res) => {
// Assume we have a function getUsers() that fetches users from a database
const users = getUsers();
res.json(users);
});
// Route to get a specific user by ID
app.get('/users/:id', (req, res) => {
// Assume getUserById(id) fetches an individual user from the database
const user = getUserById(req.params.id);
if(!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Important Info:
- Use
req.query
to access query parameters. - Use
req.params
to access route parameters. - Send back responses using methods like
res.send()
,res.json()
, orres.status()
to specify status codes explicitly.
2. Handling POST Requests
POST requests are utilized to send data to the server. This data can be in various formats, but the most common ones are JSON and URL-encoded form data. In Express.js, you often need middleware like express.json()
to parse incoming POST data.
Example:
app.use(express.json()); // Middleware to parse JSON bodies
// Route to create a new user
app.post('/users', (req, res) => {
// Assume addUser(data) inserts a new user into the database
const user = addUser(req.body);
if(!user) {
return res.status(500).json({ message: 'Internal Server Error' });
}
res.status(201).json(user); // 201 Created status code
});
Important Info:
- Typically used when submitting data to be processed to a specified resource.
- Always use
app.use(express.json())
for parsing JSON request bodies unless dealing with different content types, in which case you might need additional middleware likeexpress.urlencoded()
.
3. Handling PUT Requests
PUT requests are employed to update or replace existing resources on the server. Unlike POST requests, PUT requests imply that the client intends to send a representation of a resource that should be stored at a particular URI.
Example:
app.put('/users/:id', (req, res) => {
// Assume updateUser(id, data) updates a user in the database
const updatedUser = updateUser(req.params.id, req.body);
if(!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
res.json(updatedUser);
});
Important Info:
- A PUT request is considered idempotent — calling it multiple times will yield the same result.
- Typically sent with a request body containing data to be updated.
4. Handling DELETE Requests
DELETE requests are used to remove or delete resources identified by URIs. These requests should not require a body and generally only indicate which resource to delete.
Example:
app.delete('/users/:id', (req, res) => {
// Assume deleteUser(id) removes a user from the database
const success = deleteUser(req.params.id);
if(!success) {
return res.status(404).json({ message: 'User not found' });
}
res.status(204).send(); // 204 No Content status code indicates successful but no content returned
});
Important Info:
- Indicates a request to delete the specified resource.
- Generally does not send a request body.
- Respond with an appropriate status code like 204 (No Content) or 200 (OK) depending on your API design.
Middleware in Express.js
Middleware functions in Express.js serve as a bridge between server request/response cycle and the actual request handlers. You can attach middleware to perform operations before sending a response or handling the request.
Example:
// Logging middleware
function logger(req, res, next) {
console.log(`${req.method} ${req.path}`);
next(); // Pass control to the next function/middleware in the stack
}
app.use(logger);
app.post('/users', (req, res) => {
// Handler code...
});
Important Info:
- Middleware functions in Express.js can modify request and response objects (
req
andres
). - They are executed sequentially and can interrupt request processing by not calling
next()
.
Error Handling in Express.js
Error handling in Express.js is crucial to maintain application stability. There are several ways to handle errors, including middleware.
Example:
// Error handler middleware
app.use((err, req, res, next) => {
console.error('Error:', err.message);
res.status(err.status || 500).json({ error: err.message });
});
// Example route that triggers an error
app.get('/error', (req, res, next) => {
const err = new Error('Oops! Something went wrong.');
err.status = 500;
next(err); // Pass error to the error handler middleware
});
Important Info:
- Error-handling middlewares must have four arguments:
(err, req, res, next)
. - Ensure proper HTTP status codes are assigned to errors to indicate the nature of the problem.
Additional Considerations
- Router Objects: Organize your routes by using
express.Router()
. This allows you to modularize your code and separate concerns more effectively. - Async/Await Support: Express.js supports async/await syntax for cleaner and easier error handling in request handlers. Ensure that your handler functions are declared as
async
and use try/catch blocks for managing exceptions. - Security Best Practices: Use libraries like helmet for setting various security HTTP headers, body-parser for parsing request bodies securely, and validator for validating input data before processing.
Example with Async/Await:
Online Code run
Step-by-Step Guide: How to Implement Expressjs Handling GET, POST, PUT, DELETE Requests
Step 1: Set Up Your Project
First, ensure you have Node.js and npm installed on your machine. Then, create a new directory for your Express.js project and initialize it:
mkdir express-crud-app
cd express-crud-app
npm init -y
Install Express.js:
npm install express
Step 2: Create the Basic Express Server
Create a new file named server.js
and add the following code to set up a basic Express server:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This code does the following:
- Imports the Express module.
- Creates an instance of an Express application.
- Sets the server to listen on port 3000 and logs a message when the server is running.
- Uses
express.json()
middleware to parse JSON request bodies.
Step 3: Handle GET Requests
Let's add a simple GET route to retrieve a list of items:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];
// GET route to retrieve all items
app.get('/items', (req, res) => {
res.json(items);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Now, when you visit http://localhost:3000/items
in your browser or use a tool like Postman, you'll receive the list of items in JSON format.
Step 4: Handle POST Requests
Add a POST route to create a new item:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];
// GET route to retrieve all items
app.get('/items', (req, res) => {
res.json(items);
});
// POST route to create a new item
app.post('/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name
};
items.push(newItem);
res.status(201).json(newItem);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
To test the POST request, you can use Postman or curl:
curl -X POST http://localhost:3000/items -H "Content-Type: application/json" -d '{"name": "Item 4"}'
This will create a new item and return it with a status code of 201 (Created).
Step 5: Handle PUT Requests
Add a PUT route to update an existing item:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];
// GET route to retrieve all items
app.get('/items', (req, res) => {
res.json(items);
});
// POST route to create a new item
app.post('/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name
};
items.push(newItem);
res.status(201).json(newItem);
});
// PUT route to update an existing item
app.put('/items/:id', (req, res) => {
const itemId = parseInt(req.params.id, 10);
const updatedItem = req.body;
const itemIndex = items.findIndex(item => item.id === itemId);
if (itemIndex === -1) {
return res.status(404).json({ message: 'Item not found' });
}
items[itemIndex] = { id: itemId, name: updatedItem.name };
res.json(items[itemIndex]);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
To test the PUT request:
curl -X PUT http://localhost:3000/items/1 -H "Content-Type: application/json" -d '{"name": "Updated Item 1"}'
This will update the item with ID 1 and return the updated item.
Step 6: Handle DELETE Requests
Add a DELETE route to remove an item:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];
// GET route to retrieve all items
app.get('/items', (req, res) => {
res.json(items);
});
// POST route to create a new item
app.post('/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name
};
items.push(newItem);
res.status(201).json(newItem);
});
// PUT route to update an existing item
app.put('/items/:id', (req, res) => {
const itemId = parseInt(req.params.id, 10);
const updatedItem = req.body;
const itemIndex = items.findIndex(item => item.id === itemId);
if (itemIndex === -1) {
return res.status(404).json({ message: 'Item not found' });
}
items[itemIndex] = { id: itemId, name: updatedItem.name };
res.json(items[itemIndex]);
});
// DELETE route to remove an item
app.delete('/items/:id', (req, res) => {
const itemId = parseInt(req.params.id, 10);
const itemIndex = items.findIndex(item => item.id === itemId);
if (itemIndex === -1) {
return res.status(404).json({ message: 'Item not found' });
}
const deletedItem = items.splice(itemIndex, 1);
res.json(deletedItem);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
To test the DELETE request:
curl -X DELETE http://localhost:3000/items/1
This will delete the item with ID 1 and return the deleted item.
Complete server.js
Example
Here is the complete server.js
file with all the routes:
Login to post a comment.