Expressjs Handling GET, POST, PUT, DELETE Requests Step by step Implementation and Top 10 Questions and Answers
 Last Update:6/1/2025 12:00:00 AM     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    20 mins read      Difficulty-Level: beginner

Express.js Handling GET, POST, PUT, DELETE Requests

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. One of its primary responsibilities is handling HTTP requests from clients, including GET, POST, PUT, and DELETE. Each of these methods serves a specific purpose and is implemented differently in Express.js.

GET Request

The GET method requests a representation of the specified resource. Use the GET method to retrieve data from a server; for example, fetching user profiles, blog posts, or product data. Here’s how you can handle GET requests in Express.js:

const express = require('express');
const app = express();

app.get('/users/:id', (req, res) => {
    const userId = req.params.id;
    // Logic to fetch user data using userId
    res.json({ id: userId, name: 'John Doe' });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Important Information:

  • GET requests should never alter data on the server.
  • Data sent via GET requests is appended to the URL.
  • Ideal for retrieving information.
  • Data sent through query parameters.

POST Request

The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server. You can use POST requests to create new resources (like users, orders, products).

app.use(express.json()); // Middleware to parse JSON bodies

app.post('/users', (req, res) => {
    const userData = req.body;
    // Logic to create a new user with userData
    res.status(201).json({ message: 'User created successfully', user: userData });
});

Important Information:

  • POST requests can modify data on the server.
  • Data is sent in the request body.
  • Used when creating new resources.
  • POST requests can be cached less frequently by browsers and intermediate caches.

PUT Request

The PUT method replaces all current representations of the target resource with the uploaded content. When making a PUT request, the client sends the entire resource to the server, and the server saves it, often replacing any existing data.

app.put('/users/:id', (req, res) => {
    const userId = req.params.id;
    const userData = req.body;

    // Logic to update user data using userId and userData
    res.json({ message: 'User updated successfully', user: { ...userData, id: userId } });
});

Important Information:

  • Used to fully replace a resource.
  • Data is sent in the request body.
  • Ideal for updates where you need to send the entire resource.
  • PUT requests can be cached less frequently.

DELETE Request

The DELETE method deletes the specified resource. It is used to remove resources from the server.

app.delete('/users/:id', (req, res) => {
    const userId = req.params.id;

    // Logic to delete user using userId
    res.json({ message: 'User deleted successfully', userId: userId });
});

Important Information:

  • Deletes the specified resource from the server.
  • Generally does not take a request body.
  • Ideal for removing resources.
  • DELETE requests are idempotent (repeated requests have the same effect).

Conclusion

Express.js provides a simple and intuitive way to handle GET, POST, PUT, and DELETE requests. By following the conventions discussed, you can build robust and scalable web applications with ease. Understanding how to handle different HTTP methods correctly ensures that your application behaves predictably and efficiently, adhering to RESTful principles.

In practical applications, you often need to combine these methods with middleware for authentication, validation, and more complex business logic, thus making your Express.js applications both powerful and maintainable.




Certainly! Handling GET, POST, PUT, and DELETE requests in Express.js is a foundational concept for building robust web applications. Below, I have outlined a step-by-step guide that includes examples of setting up routes and running the application, as well as how data flows through each request type. This guide assumes you are a beginner with Node.js and Express.js.

Setting Up Your Node.js and Express.js Project

First, ensure you have Node.js and npm installed on your machine. You can download and install them from nodejs.org.

  1. Create a new directory for your project:

    mkdir express-crud-example
    cd express-crud-example
    
  2. Initialize a new Node.js project:

    npm init -y
    

    This command creates a package.json file with default configurations. -y flag auto-confirms all questions.

  3. Install Express.js:

    npm install express
    
  4. Create the main application file: Create a file named app.js or index.js. Here, we'll use app.js.

Basic Structure of app.js

This basic structure will be used throughout the document:

// Load the Express library into our project
const express = require('express');

// Creates a new instance of an Express application
const app = express();

// Middleware to parse JSON bodies
app.use(express.json());

// Define ports
const PORT = process.env.PORT || 3000;

// Start the server
app.listen(PORT, () => {
    console.log(`Server is up on port ${PORT}`);
});
  1. Run your application: To start your Express server, run the following command in your terminal:

    node app.js
    

    You should see Server is up on port 3000 in your terminal indicating that the server is running.

Handling GET Requests

GET requests are used to retrieve information from the server. We will create a simple route to return a list of items.

Example: Returning a List of Items via GET

  1. Create an array of items: Modify app.js to include an array with sample data:

    // Load the Express library
    const express = require('express');
    
    // Creates a new Express application
    const app = express();
    
    // Middleware to parse JSON bodies
    app.use(express.json());
    
    // Sample data
    const items = [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
    ];
    
    // Define a GET route
    app.get('/items', (req, res) => {
        res.json(items);
    });
    
    // Define ports
    const PORT = process.env.PORT || 3000;
    
    // Start the server
    app.listen(PORT, () => {
        console.log(`Server is up on port ${PORT}`);
    });
    
  2. Test the GET request: Use a tool like Postman or simply type http://localhost:3000/items in your browser's address bar.

    GET Request

Handling POST Requests

POST requests are used to submit data to the server to be processed, often resulting in a new item being created on the server.

Example: Adding a New Item via POST

  1. Add a POST route to handle data:

    // Existing code...
    // Define a POST route
    app.post('/items', (req, res) => {
        const newItem = {
            id: items.length + 1,
            name: req.body.name
        };
    
        items.push(newItem);
        res.status(201).json(newItem);
    });
    
  2. Test the POST request in Postman:

    • Set the request type to POST.

    • Enter http://localhost:3000/items as the URL.

    • Choose raw and select JSON as the format.

    • Add the following body content:

      {
          "name": "New Item 4"
      }
      
    • Click Send.

    POST Request

Handling PUT Requests

PUT requests are typically used to update an existing record on the server.

Example: Updating an Existing Item via PUT

  1. Add a PUT route to handle item updates:

    // Existing code...
    // Define a PUT route
    app.put('/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' });
        }
    
        items[itemIndex].name = req.body.name;
        res.json(items[itemIndex]);
    });
    
  2. Test the PUT request in Postman:

    • Set the request type to PUT.

    • Enter http://localhost:3000/items/3 as the URL.

    • Choose raw and select JSON as the format.

    • Add the following body content to change the name of the third item:

      {
          "name": "Updated Item 3"
      }
      
    • Click Send.

    PUT Request

Handling DELETE Requests

DELETE requests are used to delete a specific item from the server.

Example: Deleting an Existing Item via DELETE

  1. Add a DELETE route to handle item deletions:

    // Existing code...
    // Define a DELETE route
    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' });
        }
    
        items.splice(itemIndex, 1);
        res.json({ message: 'Item deleted successfully' });
    });
    
  2. Test the DELETE request in Postman:

    • Set the request type to DELETE.
    • Enter http://localhost:3000/items/3 as the URL.
    • Click Send.

    DELETE Request

Data Flow Step-by-Step Summary

  • GET /items:

    • Client sends a GET request to the /items route.
    • Server responds with the JSON representation of the items array.
  • POST /items:

    • Client prepares a JSON payload with the data ({ name: 'New Item 4' }) and sends it as a POST request to the /items route.
    • Server receives the JSON payload, creates a new item object based on the data received, adds it to the items array, and responds with the newly created item in JSON format.
  • PUT /items/:id:

    • Client prepares a JSON payload with updated information ({ name: 'Updated Item 3' }), sets the request type to PUT, and sends this to the /items/:id route where :id is the ID of the item to be updated (e.g., /items/3).
    • Server receives the request, checks if the item with the corresponding ID exists in the items array. If it does, the server updates the item and responds with the updated item in JSON format; otherwise, it returns a 404 error.
  • DELETE /items/:id:

    • Client sends a DELETE request to the /items/:id route where :id is the ID of the item to be deleted (e.g., /items/3).
    • Server receives the request, searches for the item with the provided ID in the items array. If found, the item is removed, and a success message is sent back to the client in JSON format. If the item doesn't exist, a 404 error is returned.

Conclusion

Through these examples, you've learned how to set up and test basic routes that handle different HTTP request methods using Express.js. Understanding how to work with GET, POST, PUT, and DELETE is critical for building full-stack applications. As you become more comfortable with these operations, you can extend the functionality of your application by integrating databases such as MongoDB, PostgreSQL, or MySQL to persist data across server restarts. Happy coding!




Certainly! Here's a comprehensive set of top 10 questions and answers focused on handling GET, POST, PUT, and DELETE requests in Express.js:

Top 10 Questions and Answers on Express.js Handling GET, POST, PUT, DELETE Requests

1. What are the HTTP methods that Express.js can handle?

Answer:
Express.js is capable of handling all standard HTTP methods including GET, POST, PUT, DELETE, and others like PATCH, OPTION, HEAD, etc. These methods are directly mapped to corresponding functions on the Express app instance (or Router instance). You can create routes using these methods, allowing your application to respond to different types of client requests.

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    // Handling GET request
});

app.post('/submit', (req, res) => {
    // Handling POST request
});

app.put('/update/:id', (req, res) => {
    // Handling PUT request
});

app.delete('/delete/:id', (req, res) => {
    // Handling DELETE request
});

2. How do you handle GET requests with Express.js?

Answer:
GET requests are typically used to retrieve data from the server without modifying it. In Express, you define a GET route using app.get() method, specifying the path and a callback function that sends a response back to the client.

Here is an example where we fetch data about a user:

app.get('/user/:id', (req, res) => {
    const userId = req.params.id;
    // Find user details based on 'userId'
    User.findById(userId, (err, user) => {
        if (err) return res.status(400).send('Error fetching user');
        if (!user) return res.status(404).send('User not found');

        res.send(user); // Send user details
    });
});

Note: We access URL parameters via req.params.

3. Can you explain how to parse query strings in GET requests using Express.js?

Answer:
Query strings are commonly used in GET requests to send additional information via the URL. In Express.js, query string parameters are accessible through req.query.

Example URL: http://example.com/api/products?page=2&category=laptops

app.get('/api/products', (req, res) => {
    const page = parseInt(req.query.page) || 1; // Default to page 1 if not provided
    const category = req.query.category;        // Fetch category from the query string

    Product.find({ category })
        .skip((page - 1) * 10)
        .limit(10)
        .exec((err, products) => {
            if (err) return res.status(400).send(err);
            
            res.json(products); // Respond with JSON array of products
        });
});

4. How should you handle POST requests when receiving form data in Express.js?

Answer:
To handle POST requests that include form data in Express.js, you need middleware to parse the body of the request. For URL-encoded data, use express.urlencoded(). For JSON payloads, use express.json().

app.use(express.json());       // To parse JSON bodies
app.use(express.urlencoded()); // To parse URL-encoded data (useful for form submissions)

app.post('/login', (req, res) => {
    const { username, password } = req.body;

    User.authenticate(username, password, (err, user) => {
        if (err) return res.status(400).send(err.message);
        if (!user) return res.status(403).send('Access denied');
        
        res.send('Login successful');
    });
});

5. How can you handle multipart/form-data in POST requests using Express.js?

Answer:
Handling multipart/form-data, such as uploading files through forms, can be done using external libraries like multer. Here’s an example:

First, you need to install multer:

npm install multer

Then use multer in your app:

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('image'), (req, res) => {
    // 'image' is the name attribute of the input file field in the form.
    console.log(req.file); // File information
    console.log(req.body); // Form fields other than the file

    res.status(201).send('File uploaded successfully');
});

You can also save files to a custom directory or even stream them. Refer to the Multer documentation for more details.

6. What is the difference between PUT and PATCH requests, and how would you handle them in Express.js?

Answer:
PUT and PATCH both modify resources on the server but with different intentions. PUT replaces the entire target resource with the content provided in the request, making it idempotent (i.e., multiple identical requests cause no harm). PATCH only applies partial modifications to the target resource and is also intended to be non-destructive.

Here’s how you might handle PUT and PATCH:

For a PUT request:

app.put('/item/:id', (req, res) => {
    const itemId = req.params.id;
    const newItemData = req.body;

    Item.findByIdAndUpdate(itemId, newItemData, {new: true}, (err, item) => {
        if (err) return res.status(400).send('Update failed');
        if (!item) return res.status(404).send('Item not found');

        res.send(item); // Sends updated item data
    });
});

For a PATCH request (only updates fields provided):

app.patch('/item/:id', (req, res) => {
    const itemId = req.params.id;
    const updateFields = req.body;

    Item.findByIdAndUpdate(itemId, {$set: updateFields}, {new: true}, (err, item) => {
        if (err) return res.status(400).send('Update failed');
        if (!item) return res.status(404).send('Item not found');

        res.send(item); // Sends updated item data
    });
});

7. How do you implement DELETE functionality in Express.js?

Answer:
DELETE requests are used to remove a specific resource identified by its ID. Similar to other CRUD operations, you first identify which resource to delete and then execute the delete operation on the database.

Here’s an example of handling a DELETE request:

app.delete('/item/:id', (req, res) => {
    const itemId = req.params.id;

    Item.findByIdAndRemove(itemId, (err) => {
        if (err) return res.status(400).send('Delete failed');

        res.status(204).end(); // Return empty response with status code of 204 No Content
    });
});

Important: Always ensure proper security checks are in place before executing a delete operation to prevent accidental or unauthorized deletions.

8. Can you provide a full example of an Express.js application that handles all CRUD operations?

Answer:
Sure, here’s a simple Express.js application with routes for handling GET, POST, PUT, and DELETE operations on a collection of users.

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();
app.use(bodyParser.json());

// Connecting to MongoDB database
mongoose.connect("mongodb://localhost:27017/testDB", { useNewUrlParser: true, useUnifiedTopology: true });

// Defining User schema/model
const UserSchema = new mongoose.Schema({
    name: String,
    email: String
});
const User = mongoose.model("User", UserSchema);

// CREATE (POST)
app.post("/users", async (req, res) => {
    try {
        const newUser = new User(req.body);
        await newUser.save();
        res.status(201).send(newUser);
    } catch (e) {
        res.status(400).send(e.message);
    }
});

// READ (GET)
app.get("/users", async (req, res) => {
    try {
        const users = await User.find({});
        res.status(200).send(users);
    } catch (e) {
        res.status(500).send(e.message);
    }
});

app.get("/users/:id", async (req, res) => {
    try {
        const user = await User.findById(req.params.id);
        if (!user) return res.status(404).send('User not found');
        
        res.status(200).send(user);
    } catch (e) {
        res.status(400).send(e.message);
    }
});

// UPDATE (PUT/PATCH)
app.put("/users/:id", async (req, res) => {
    try {
        const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
        if (!user) return res.status(404).send('User not found');
        
        res.status(200).send(user);
    } catch (e) {
        res.status(400).send(e.message);
    }
});

// DELETE (DELETE)
app.delete("/users/:id", async (req, res) => {
    try {
        const user = await User.findByIdAndRemove(req.params.id);
        if (!user) return res.status(404).send('User not found');
        
        res.status(204).end();
    } catch (e) {
        res.status(400).send(e.message);
    }
});

// Listening on port 3000
app.listen(3000, () => {
    console.log("Server started on port 3000...");
});

In this example:

  • We connect to a MongoDB database using Mongoose.
  • Users are represented by a simple schema with name and email.
  • The app.post route creates a new user record.
  • The app.get routes fetch all users or a specific user by their ID.
  • The app.put route update an existing user entirely.
  • The app.delete route removes a user by their ID.

9. How do you validate request data in Express.js?

Answer:
Validating incoming request data is crucial to maintaining robust APIs and preventing data corruption. A popular library for data validation in Express.js is Joi.

Installation:

npm install joi

Example usage for validating a POST request:

const Joi = require("joi");

app.post("/users", (req, res) => {
    // Define validation schema
    const schema = Joi.object({
        name: Joi.string().alphanum().min(3).max(30).required(),
        email: Joi.string().email().required()
    });

    // Validate request body against the schema
    const { error, value } = schema.validate(req.body);

    if (error) {
        return res.status(400).send(error.details[0].message);
    }

    // If valid, proceed with creating the user
    const user = new User(value);
    user.save().then(() => res.send(user)).catch((e) => res.status(500).send(e.message));
});

This validates whether name and email fields meet specific criteria before processing further.

10. How can middleware in Express.js be used to preprocess requests before they reach the handler?

Answer:
Middleware functions are essentially handlers executed before the main route handler. They can be used to perform common preprocessing tasks such as logging, authentication, parsing headers, and sanitizing inputs.

Example of Middleware in Express.js:

a) Logging middleware

app.use((req, res, next) => {
    console.log(`${req.method} request for ${req.url}`);
    next(); // Pass control to the next middleware/route handler
});

b) Authentication middleware

function authenticate(req, res, next) {
    const authHeader = req.headers['authorization'];
    // Check if authorization header is present and valid token exists
    if (!authHeader) return res.status(401).send('Authorization token required');

    const token = authHeader.split(' ')[1]; 

    // Verify token (assuming JWT is used here)
    jwt.verify(token, 'your-secret-key', (err, user) => {
        if (err) return res.status(403).send('Invalid token');
        
        req.user = user; // Attach user object to req
        next();
    });
}

// Apply this authentication middleware globally or per specific routes
app.use(authenticate);

// Or only for some specific routes
app.get('/dashboard', authenticate, (req, res) => {
    // Handler logic here
    res.send(`Welcome ${req.user.name} to your dashboard`);
});

In summary, middleware functions are added via app.use() or specified directly as part of a route definition. They receive the same three arguments as regular route handlers (req, res, next), and can terminate the execution chain by returning a response or call next() to pass the request along.

By understanding these concepts, you can effectively manage and structure HTTP requests within an Express.js application, ensuring clean, secure, and efficient handling of user data across various CRUD operations.