A Step-by-Step Guide to Handle Query Parameters in Node.js

69 views

Managing query parameters and query strings in a Node.js HTTP server without using external libraries like Express.js involves parsing the URL to extract these values. Here's a step-by-step guide on how to handle query parameters and query strings in your simple server:

Step 1: Modify the Router to Handle Query Parameters

  1. Update router.js:
    const url = require('url');
    const querystring = require('querystring');
    
    const routes = {
      '/': require('./routes/index'),
      '/about': require('./routes/about')
    };
    
    const router = (req, res) => {
      const parsedUrl = url.parse(req.url);
      const pathname = parsedUrl.pathname;
      const queryParams = querystring.parse(parsedUrl.query);
    
      req.queryParams = queryParams; // Attaching queryParams to the request object
    
      const handler = routes[pathname] || require('./routes/notFound');
      handler(req, res);
    };
    
    module.exports = router;
    

Step 2: Use Query Parameters in Route Handlers

  1. Update routes/index.js to utilize query parameters:

    const index = (req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
    
      // Use query parameters if available
      const name = req.queryParams.name || 'World';
      res.end(`Hello, ${name}!\n`);
    };
    
    module.exports = index;
    
  2. For demonstration, update routes/about.js to utilize query parameters:

    const about = (req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
    
      // Use query parameters if available
      const detail = req.queryParams.detail || 'default detail';
      res.end(`About Page: ${detail}\n`);
    };
    
    module.exports = about;
    

Step 3: Running the Server

  1. In your terminal, restart the server:

    node server.js
    
  2. You should see the following output in your terminal:

    Server running at http://127.0.0.1:3000/
    

Step 4: Testing Query Parameters

  1. Open your web browser or use a tool like curl to test the server:
    • Visit http://127.0.0.1:3000/?name=John to see the "Hello, John!" message.
    • Visit http://127.0.0.1:3000/about?detail=specific%20info to see the "About Page: specific info" message.
    • Visit http://127.0.0.1:3000/about to see the "About Page: default detail" message.

Explanation of the Code

  1. Parsing URL:

    • Import the url and querystring modules:
      const url = require('url');
      const querystring = require('querystring');
      
  2. Extracting Pathname and Query Parameters:

    • In router.js:
      const parsedUrl = url.parse(req.url);
      const pathname = parsedUrl.pathname;
      const queryParams = querystring.parse(parsedUrl.query);
      
      • url.parse(req.url) parses the URL and extracts the pathname and query string.
      • querystring.parse(parsedUrl.query) parses the query string into an object.
  3. Attaching Query Parameters to Request Object:

    req.queryParams = queryParams;
    
    • Attach the parsed query parameters to the req (request) object for easier access in route handlers.
  4. Using Query Parameters in Route Handlers:

    • In routes/index.js:
      const name = req.queryParams.name || 'World';
      
    • In routes/about.js:
      const detail = req.queryParams.detail || 'default detail';
      
      • Retrieve and use query parameters within the route handlers.

By implementing these changes, you can effectively manage query parameters and query strings in your Node.js server without using external libraries. This approach allows you to handle dynamic content and improve the interactivity of your server with client requests.