Adding Basic Routing - 7.7 | Chapter 7: Backend Basics with Node.js | Full Stack Web Development Basics
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skillsβ€”perfect for learners of all ages.

games

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to Routing

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Today, we're diving into routing for our Node.js server. Can anyone tell me what routing means?

Student 1
Student 1

I think it has to do with directing users to different parts of a website based on what they click.

Teacher
Teacher

Exactly, routing helps us manage where users go when they visit different URLs. It allows our server to respond differently based on the request. Remember, URLs represent paths to specific resources.

Student 2
Student 2

So, if I go to my homepage, I would get different content compared to going to the about page?

Teacher
Teacher

Correct! Let's explore how we can implement this in our code.

Implementing Basic Routing

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

To implement basic routing, we will modify our server code. Here's how to get started: First, we check the URL using `req.url`.

Student 3
Student 3

How do we respond differently based on that?

Teacher
Teacher

We can use `if` statements to check what the `req.url` is. For example, if it’s `'/about'`, we respond with information about us.

Student 4
Student 4

What happens if someone types a URL that doesn't exist?

Teacher
Teacher

Great question! We set a default response for any unknown URL, letting the user know the page isn't found.

Testing the Routing

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Now that we've set up our routing, let's think about testing it. Can someone tell me what URLs to test?

Student 1
Student 1

We should check `http://localhost:3000/` for the homepage.

Student 2
Student 2

And `http://localhost:3000/about` for the about page.

Teacher
Teacher

Exactly! If we input the wrong path, like `http://localhost:3000/contact`, we should see our 'Page not found' message.

Student 3
Student 3

That’s cool! So we have some control over the content that users see.

Recap and Application

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

To recap, we learned how to add basic routing to our Node.js server. This allows different responses based on the URL.

Student 4
Student 4

Routing is important for creating a user-friendly experience online.

Teacher
Teacher

Absolutely! As we advance, routing will become even more vital, especially for creating APIs. Can anyone think of other routes we might want to add?

Student 1
Student 1

We could have a contact page or a list of services!

Teacher
Teacher

Exactly! More routes can lead to a richer web application.

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

This section teaches how to implement basic routing in a Node.js server to respond to different URLs.

Standard

In this section, you will learn how to configure your Node.js server to respond differently based on the incoming URL by adding routing logic. This enables your backend to handle various requests and provide appropriate responses.

Detailed

Adding Basic Routing

In this section, we explore how to make a Node.js web server respond differently based on the incoming URL. Routing is crucial for web applications as it allows servers to direct users to various parts of an application based on their requests.

To implement basic routing, we modify the server code by checking the req.url property, which contains the URL of the incoming request.

Basic Routing Code Example

Code Editor - javascript

How it Works

  • The req.url is checked for specific routes ("/" for the homepage and "/about" for the about page).
  • If it matches a defined route, a specific message is written to the response.
  • If the route does not match any defined paths, a default message indicating that the page is not found is sent.

Testing the Routes

By running the server and navigating to:
- http://localhost:3000/ β†’ Displays "Welcome to the homepage!"
- http://localhost:3000/about β†’ Displays "This is the about page."
- Accessing any other path will return "Page not found."

Understanding routing in Node.js lays the foundation for more complex server-side logic in future applications.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Setting Up Routing in the Server

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Let’s make the server respond differently based on the URL.

const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.write("Welcome to the homepage!");
} else if (req.url === "/about") {
res.write("This is the about page.");
} else {
res.write("Page not found.");
}
res.end();
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});

Detailed Explanation

In this chunk, we configure the Node.js server to respond based on the URL requested by the user. We first set up a server using the http module. Inside the createServer function, we check the req.url property, which contains the path of the requested URL. If it matches certain conditions, we respond with different messages. Specifically, if the URL is the root ("/"), we send a welcome message. If the URL is "/about", we send a message about the page. If neither condition is met, we return a 'Page not found' message. Finally, we finish the response using res.end() to send it back to the user.

Examples & Analogies

Think of your server like a receptionist at a hotel. When someone walks up to the desk (the server receives a request), the receptionist checks what the guest is asking for (the requested URL). If a guest asks for the main lobby ("/"), the receptionist welcomes them to the lobby. If they ask for the business center ("/about"), the receptionist guides them there. However, if they ask for an area that doesn't exist, like a swimming pool, the receptionist politely informs them that it isn't available.

Starting the Server

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

Now try these in your browser:
- http://localhost:3000/ β†’ homepage
- http://localhost:3000/about β†’ about page
- Anything else β†’ page not found

Detailed Explanation

After setting up routing in our server, we can test it by opening our web browser and navigating to the specified URLs. When we visit http://localhost:3000/, we should see the homepage message. When we go to http://localhost:3000/about, we're directed to the about page message. If we enter any other URL, the server will respond with a message that says 'Page not found'. This testing helps us ensure that the routing works as intended.

Examples & Analogies

Imagine you're exploring different sections of a library. If you walk into the general reading room (the homepage), the librarian welcomes you. If you ask about the history section (the about page), the librarian guides you there. However, if you walk into a restricted area (any URL that doesn't exist), the librarian tells you that entry is not allowed. This way, each URL corresponds to a different area of information you might need.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • Routing: The mechanism that directs requests to specific sections of a web server based on URL.

  • req.url: A Node.js property used to determine which URL is being requested.

  • Response messages: The server's replies tailored based on the URL accessed.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • If the user accesses http://localhost:3000/, they see 'Welcome to the homepage!'.

  • Accessing http://localhost:3000/about results in 'This is the about page.'.

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎡 Rhymes Time

  • When a request you do pursue, the URL tells us what to view.

πŸ“– Fascinating Stories

  • Imagine a postman delivering letters; he checks the address on each envelope to deliver it to the right house. Similarly, our server checks the URL to send the right response.

🧠 Other Memory Gems

  • Remember VPS: View, Path, Server. Check the View (URL), determine the Path, then send the response from the Server.

🎯 Super Acronyms

RAP

  • Routing And Processing. This can remind you that routing leads to processing user requests.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: Routing

    Definition:

    The process of directing users to different resources based on their requested URL.

  • Term: req.url

    Definition:

    A property in Node.js that contains the URL of the incoming request.

  • Term: Response

    Definition:

    The data sent by the server back to the client in response to their request.