DEV Community

WebCraft Notes
WebCraft Notes

Posted on • Updated on • Originally published at webcraft-notes.com

Node.js Basis: Routing and Parameterized URLs Guide

Node.js Basis: Routing and Parameterized URLs Guide

Also check this post in my web notes.

In our previous post, we laid the foundation by creating a straightforward Node.js web server. While this server suffices for a single-page web application, it prompts new questions when dealing with multiple pages or dynamic content. What if we're managing numerous pages or envision a scenario with hundreds of posts that need dynamic rendering in the browser? To tackle these challenges head-on, we'll delve into the world of routing and parameters to enhance our simple web server's capabilities.

Let's remember where we finished last time and continue by adding routing so that we can show different data in response to changing routes in our web app.

const http = require('http');
const port = 3000;
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, this is a simple web server!');
});

server.listen(port, () => {
  console.log(`Server running at localhost:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

Node.js Routing

Okay, now we will use data from "req" to receive and check URLs with conditional statements. Each condition will be a different route, and depending on the condition we will send another response to the user. Also in our final "else" condition we will handle all unknown routes and rewrite the header with a 404 error. Here is how our server will look after changes:

const http = require('http');
const port = 3000;
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    if (req.url === '/') {
      res.end('Welcome to the homepage!');
    } else if (req.url === '/about') {
      res.end('This is the About page.');
    } else if (req.url === '/users') {
      res.end('Contact us at contact@example.com');
    } else {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('404 - Page Not Found');
    }
});

server.listen(port, () => {
  console.log(`Server running at localhost:${port}/`);
});
Enter fullscreen mode Exit fullscreen mode

Now we will execute the "node simpleWebServer.js" command in the terminal and check the result. Also don't forget to use different routes. And here is what we get:
first Node js url result image

Node.js Parameterized URLs

Let's add the "users" array as a small database, then we will refactor our code a little bit. First, we will split the URL into parts with "/" as a divider, and store the resulting array in the "items" variable. Our third item in an array will be our "user-id" for example, so we can check and return users' data.

Next inside our conditional statement where it checks "users" we will add a new condition that will see if our "items" array length has 3 items and if yes then it has a user parameter and we need to find and return user data inside response but previously transform into JSON, if not we will return all users.

Continue reading...

Top comments (0)