Basic Routing

Set up basic routing in Node.js to control how the server responds to different URLs and requests.

In web development, routing refers to defining how a server handles incoming client requests based on the requested URL and HTTP method. It serves as a blueprint for directing requests to the appropriate responses, enabling the server to serve different purposes dynamically. For example, routing can be used to display a homepage, retrieve or submit data, handle user authentication, or show an error message for unknown routes.

By implementing routing, a server can map specific URLs or request patterns to dedicated logic, making it flexible and capable of handling various client needs. This approach is foundational for building interactive web applications and APIs, as it allows developers to create tailored responses for different endpoints, such as /about, /api/data, or /404.

Node.js’s event-driven, non-blocking architecture makes it especially effective for handling multiple routes in a single server. In this lesson, we’ll create a basic server that serves different responses depending on the requested URL.

How routing works in Node.js

Routing in Node.js is based on examining the req.url property, which contains the URL path of the client’s request. By checking req.url and req.method, we can define routes to handle specific requests:

  • / can serve as the homepage.

  • /about can provide information about the application.

  • Additional routes can be added to serve data or perform specific actions.

This enables us to build a flexible server that serves different content depending on the client’s request.

Setting up routes with the http module

Let’s add routing to our server to respond differently to each URL. To add basic routing:

  1. Import the http module.

  2. Create a server using http.createServer().

  3. Check the req.url and req.method properties inside the server callback.

  4. Use res.write() and res.end() to send different responses based on the requested route.

Note: When you click the “Run” button, the server will start automatically. You can test it by opening the provided URL in a new browser tab and appending different endpoints to it.