
Lesson Description
The "Subrouters" Lesson is part of the full, API Design in Node.js, v5 course featured in this preview video. Here's what you'd learn in this lesson:
Scott demonstrates how to create sub-routers in Express for resources like users, habits, and authentication, setting up CRUD routes and handling habit completions. He also covers HTTP status codes, emphasizing proper use of success and error responses.
Transcript from the "Subrouters" Lesson
[00:00:00]
>> Speaker 1: Okay, let's create the routing for the app I'll scroll to it The first thing we're going to do is create some sub-routers, which are routers that we can mount on a top-level router
[00:00:00]
We'll go into our source folder, make a new folder called Routes, and for each resource we'll create a file for its router We'll have User Routes, Habit Routes, and All Routes
[00:00:00]
The way this will look is that each will be an individual sub-router that we can mount onto the top-level router We'll import the Router from Express, and then create a router using Router()
[00:00:00]
I don't know why they still haven't changed this in Express V5, but I digress We'll set up the CRUD routes For the Auth Routes, it's slightly different since authentication isn't exactly a resource - it's more of a mechanism
[00:00:00]
We'll use router methods just like we would with an app For authentication, we'll create a post route for registration We'll use status 201, which technically means a successful post request
[00:00:00]
In practice, 200 and 201 are quite similar We'll add a placeholder response of "user signed up" We'll add another post route for login, with a similar placeholder response of "user logged in"
[00:00:00]
Remember, to import a module, you must export it first A module is essentially a closure, and exporting allows other parts of the application to access it
[00:00:00]
For the Habit Routes, we'll create more comprehensive CRUD routes We'll have routes to:
- Get all habits (GET /)
- Get a single habit (GET /:id)
- Create a habit (POST /)
- Delete a habit (DELETE /:id)
We'll also add a custom route to complete a habit (POST /complete/:id), which breaks from strict REST conventions
[00:00:00]
As the server developer, you have the flexibility to define routes as needed Most routes will default to a 200 status code While there are specific status codes for different actions (like 201 for successful creation), in practice, you'll most commonly see 200 and 201
[00:00:00]
Developers tend to be more precise with 400-series error codes since they're user-facing The key point is the flexibility of server-side routing - you can essentially create routes that make sense for your specific application's needs.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops