| 2024-03-18

Express server API request object

    Starting where we left off from the previous post about creating a basic Express server, we'll explore various Express server APIs that handle incoming data using the req object.

    In the Express framework, incoming data is represented by the req object, short for "request". This object contains information about the incoming HTTP request made by the client to the server.

    The incoming data contained in the req object can come from various sources depending on the type of request and how it's made. Here are some common sources of incoming data:

    Table of Contents

    1. API that takes in a URL parameter

    2. API that takes in a query parameter

    3. API that handles request body data

    4. API that handles request headers


    1. Express server API that takes in a URL parameter

    We'll create a route that responds with the value of the URL parameter.

    Here's how you can do it:

    1. First, make sure you have Express installed in your project. If not, you can install it using npm:
    npm install express
    
    bash
    1. Create a file named index.js:
    touch index.js
    
    bash
    1. Open index.js in a text editor and add the following code:
    const express = require("express");
    const app = express();
    
    // Define a route that takes a URL parameter
    app.get("/users/:id", (req, res) => {
      const userId = req.params.id;
      res.send(`User ID: ${userId}`);
    });
    
    // Start the server
    app.listen(3000, () => {
      console.log("Server is running on port 3000");
    });
    
    javascript

    In this example:

    • We define a route /users/:id, where :id is a placeholder for the user's ID.
    • When a GET request is made to this route, Express extracts the value of the id parameter from the URL and stores it in req.params.id.
    • We then send a response back to the client with the user ID extracted from the URL parameter.
    1. Now, you can start the server by running:
    node index.js
    
    bash

    Your server will now be running on port 3000.

    1. To test the endpoint, you can make a GET request to http://localhost:3000/users/123, replacing 123 with any user ID you want to test with. You should receive a response indicating the user ID you provided in the URL parameter. For example, if you visit http://localhost:3000/users/123, you should see User ID: 123 as the response.

    That's it! You've created an Express server API that takes in a URL parameter. You can now expand upon this example to handle more complex scenarios or add additional routes and functionality as needed.

    2. Express server API that takes in a query parameter

    Create an Express server API that handles query parameters:

    const express = require("express");
    const app = express();
    
    // Define a route that handles query parameters
    app.get("/search", (req, res) => {
      const query = req.query.query;
      res.send(`Search Query: ${query}`);
    });
    
    // Start the server
    app.listen(3000, () => {
      console.log("Server is running on port 3000");
    });
    
    javascript

    In this example:

    • We define a route /search to handle requests with query parameters.
    • When a GET request is made to this route with query parameters (e.g., /search?query=express), Express automatically parses the query parameters and makes them available in the req.query object.
    • We extract the value of the query parameter from req.query and send a response back to the client indicating the search query.

    To test the endpoint, you can make a GET request to http://localhost:3000/search?query=example, replacing example with any search query you want to test with. You should receive a response indicating the search query you provided in the query parameter. For example, if you visit http://localhost:3000/search?query=express, you should see Search Query: express as the response.

    3. Express server API that handles request body data

    Here's a simple example of an Express server API that handles requests with a request body:

    const express = require("express");
    const app = express();
    
    // Middleware to parse JSON bodies
    app.use(express.json());
    
    // Define a route that handles POST requests with a JSON request body
    app.post("/submit", (req, res) => {
      const { name, email } = req.body;
      res.send(`Submitted: Name - ${name}, Email - ${email}`);
    });
    
    // Start the server
    app.listen(3000, () => {
      console.log("Server is running on port 3000");
    });
    
    javascript

    In this example:

    • We've added middleware express.json() to our Express application. This middleware is used to parse incoming JSON requests.
    • We define a route /submit to handle POST requests.
    • When a POST request is made to this route with a JSON request body, Express parses the JSON data and makes it available in the req.body object.
    • We extract the name and email fields from the request body using object destructuring.
    • We send a response back to the client indicating the submitted data.

    To test the endpoint, you can make a POST request to http://localhost:3000/submit with a JSON request body. For example:

    curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com"}' http://localhost:3000/submit
    
    bash

    You should receive a response indicating the submitted data. For example:

    Submitted: Name - John Doe, Email - john@example.com
    
    bash

    4. Express server API that handles request headers

    Here's a simple example of an Express server API that accesses request headers:

    const express = require("express");
    const app = express();
    
    // Define a route that handles GET requests
    app.get("/headers", (req, res) => {
      // Accessing request headers
      const userAgent = req.headers["user-agent"];
      const contentType = req.headers["content-type"];
    
      // Sending response with headers information
      res.send(`User-Agent: ${userAgent}, Content-Type: ${contentType}`);
    });
    
    // Start the server
    app.listen(3000, () => {
      console.log("Server is running on port 3000");
    });
    
    javascript

    In this example:

    • We define a route /headers to handle GET requests.
    • Within the route handler function, we access request headers using req.headers.
    • We specifically access the user-agent and content-type headers.
    • We then send a response back to the client with information about these headers.

    To test the endpoint, you can make a GET request to http://localhost:3000/headers using cURL. You can use the following command:

    curl -H "Content-Type: application/json" http://localhost:3000/headers
    
    
    bash

    You should receive a response containing information about the User-Agent and Content-Type headers.


    Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.