feat(curriclum): add routing express lesson block (#66250)

Co-authored-by: majestic-owl448 <26656284+majestic-owl448@users.noreply.github.com>
Co-authored-by: Ilenia M <nethleen@gmail.com>
This commit is contained in:
Zaira
2026-04-24 23:25:01 +05:00
committed by GitHub
parent 8762c1bb49
commit 15845505db
11 changed files with 1478 additions and 1 deletions
+7
View File
@@ -7220,6 +7220,13 @@
"In these lessons, you will learn what Express.js is, why developers use it for building web servers and APIs, and how to set up a basic Express application with routes and request handling."
]
},
"lecture-understanding-routing-in-express-js": {
"title": "Understanding Routing in ExpressJS",
"intro": [
"Understanding Routing in ExpressJS",
"In these lessons, you will learn about routing in ExpressJS, which is how you define the different endpoints of your web application and how they respond to client requests."
]
},
"exam-back-end-development-and-apis-certification": {
"title": "Back-End Development and APIs Certification Exam",
"intro": [
@@ -0,0 +1,177 @@
---
id: 69a848d4f1d1b4b9e176a026
title: What Is Routing and How Do Route Methods Work in Express?
challengeType: 19
dashedName: what-is-routing-and-how-do-route-methods-work-in-express
---
# --description--
Now that you've built a basic Express app, it's time to take a closer look at routing and how it works.
In Express, routing is how you define the endpoints of a web application. You can think of routes as rules that tell the app how to respond when a user visits a specific URL.
Let's look at our simple Express app again:
```javascript
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
```
In this example, the app defines a route for the root URL (`/`). When a client sends a GET request to this path, the server responds with the text `Hello World!`. The app then starts listening for incoming requests on port `3000`.
But there are other route methods.
Express lets you handle different types of HTTP requests by using different routing methods. The most common ones are:
* `app.get()` retrieves data
* `app.post()` creates new data
* `app.put()` updates existing data
* `app.delete()` deletes data
Each method defines how your application should respond to a specific HTTP request at a specific route.
Here are a few simple examples:
```javascript
app.post("/submit", (req, res) => {
res.send("Form submitted!");
});
app.put("/update", (req, res) => {
res.send("Item updated!");
});
app.delete("/delete", (req, res) => {
res.send("Item deleted!");
});
```
In each case, Express listens for a request with a particular HTTP method and URL path, then runs the corresponding handler function to send a response back to the client.
You can test these routes using tools like Postman or `curl`, which let you send different types of HTTP requests to your server.
And thats routing in Express - its simply about defining how your application responds to different requests.
# --questions--
## --text--
What does `app.get('/', ...)` do?
## --answers--
It deletes the homepage.
### --feedback--
Think about what happens when a user visits `/`.
---
It creates a database.
### --feedback--
Think about what happens when a user visits `/`.
---
It responds to a GET request at the root URL.
---
It shuts down the server.
### --feedback--
Think about what happens when a user visits `/`.
## --video-solution--
3
## --text--
Which route method would you use to update an existing item?
## --answers--
`app.get()`
### --feedback--
Think about the method used for updates.
---
`app.post()`
### --feedback--
Think about the method used for updates.
---
`app.put()`
---
`app.delete()`
### --feedback--
Think about the method used for updates.
## --video-solution--
3
## --text--
What do Express route methods like `app.get()` or `app.post()` do?
## --answers--
They start the server listening on a port.
### --feedback--
Think about how Express knows what to do when a request is made to a certain URL.
---
They connect the app to a database.
### --feedback--
Think about how Express knows what to do when a request is made to a certain URL.
---
They define how the app responds to specific HTTP requests and URLs.
---
They stop the server.
### --feedback--
Think about how Express knows what to do when a request is made to a certain URL.
## --video-solution--
3
@@ -0,0 +1,166 @@
---
id: 69a9182c1bc7cc1a76116635
title: What Are Route Paths in Express?
challengeType: 19
dashedName: what-are-route-paths-in-express
---
# --description--
In Express, **route paths** are the URL patterns that determine how the server responds to incoming requests. When a user requests a specific URL, Express matches that URL to a route path and runs the corresponding handler.
Route paths are defined inside route methods like `app.get()`, `app.post()`, and so on. These paths can be static, such as `/home`, or dynamic, where parameters are used to capture values from the URL, like `/user/:id`.
In this lesson well focus on static routes. Heres an example of one:
```javascript
// Static route
app.get("/home", (req, res) => {
res.send("Welcome to the homepage!");
});
```
In this example, the server listens for GET requests to `/home` and responds with a simple message.
The `app.get()` method takes two arguments:
* The first argument, `"/home"`, is the static route path (or URL) that the server listens for.
* The second argument is a callback function that runs when a GET request is made to that path.
Inside the callback, `res.send()` sends a response back to the client. In this case, it sends the text `Welcome to the homepage!`, which is displayed in the browser.
Heres another example of a static route:
```javascript
// Static route
app.get("/menu/drinks", (req, res) => {
res.send("Welcome to the drinks menu!");
});
```
In this case, the server listens for GET requests to the `/menu/drinks` URL and sends back a message when that route is requested.
You might use routes like this when your site has multiple related pages grouped under a common path. For example, a restaurant website could organize its menu pages like this:
* `/menu/food`
* `/menu/drinks`
* `/menu/desserts`
This approach helps keep your URLs clear and meaningful, and it also makes your routes easier to organize and maintain as your application grows.
In the next lesson, well look at dynamic route paths with parameters.
# --questions--
## --text--
What does the route `app.get("/home", ...)` respond to?
## --answers--
POST requests to `/home`
### --feedback--
Look at the first parameter.
---
GET requests to `/home`
---
GET requests to `/menu/drinks`
### --feedback--
Look at the first parameter.
---
POST requests to `/menu/drinks`
### --feedback--
Look at the first parameter.
## --video-solution--
2
## --text--
What does the route `app.get("/menu", ...)` respond to?
## --answers--
POST requests to `/menu`
### --feedback--
Look at the first parameter.
---
GET requests to `/menu`
---
GET requests to `/menu/drinks`
### --feedback--
Look at the first parameter.
---
POST requests to `/menu/drinks`
### --feedback--
Look at the first parameter.
## --video-solution--
2
## --text--
What does the route `app.get("/menu/drinks", ...)` respond to?
## --answers--
POST requests to `/menu`
### --feedback--
Look at the first parameter.
---
GET requests to `/menu`
### --feedback--
Look at the first parameter.
---
GET requests to `/menu/drinks`
---
POST requests to `/menu/drinks`
### --feedback--
Look at the first parameter.
## --video-solution--
3
@@ -0,0 +1,163 @@
---
id: 69a91831ef910efdde054a5a
title: What Are Route Parameters?
challengeType: 19
dashedName: what-are-route-parameters
---
# --description--
In Express, route parameters are dynamic values embedded in the URL path. They let your application capture parts of the URL that can change with each request. This is useful for building dynamic pages, like displaying a specific user, blog post, or product based on the URL.
Heres an example:
```javascript
// Route with a parameter in the path
app.get("/post/:postId", (req, res) => {
const postId = req.params.postId;
res.send(`Viewing post with ID: ${postId}`);
});
```
Here, the route listens for GET requests to `/post/:postId`.
* `:postId` is a route parameter, a placeholder in the URL that will be replaced by an actual value. For example, a request to `/post/42` matches this route, and `42` becomes the value of `postId`.
* You can access route parameters using `req.params`. The `req.params` object contains all route parameters, and in this case, `req.params.postId` contains the value from the URL, `42`.
Finally, `res.send()` sends a response back to the client. So if the URL is `/post/42`, the client sees `Viewing post with ID: 42`.
So as you can see, route parameters make your routes flexible and dynamic without needing a separate route for every possible value.
Now that you understand how route parameters work, lets go back to an example from the last lesson and see how you can use dynamic routes for different types of menus:
```javascript
app.get("/menu/:category", (req, res) => {
const category = req.params.category;
res.send(`You are viewing the ${category} menu!`);
});
```
And heres a breakdown of how this works:
1. A user visits [`http://localhost:3000/menu/drinks`](http://localhost:3000/menu/drinks).
2. The server matches this request to the route `/menu/:category` and captures the `category` parameter as `drinks`.
3. The server sends this response back to the browser: `You are viewing the drinks menu!`
Similarly, if the user visits [`http://localhost:3000/menu/food`](http://localhost:3000/menu/food), the server responds with the following: `You are viewing the food menu!`
Route parameters let you display dynamic content based on the URL. Instead of creating a separate route for every category, you can use a single route to handle multiple categories like drinks, food, desserts, and more, simply by changing the URL.
# --questions--
## --text--
What is the role of `:postId` in the route `/post/:postId`?
## --answers--
It is a static part of the URL.
### --feedback--
`:` indicates a parameter, not a fixed segment.
---
It captures a dynamic value from the URL.
---
It is a query parameter.
### --feedback--
Query parameters appear after `?`, not within the path.
---
It defines a custom header.
### --feedback--
Route parameters live in the URL path, not headers.
## --video-solution--
2
## --text--
What would `req.params.postId` contain when the URL is `/post/100`?
## --answers--
`100`
---
`postId`
### --feedback--
`req.params` holds the actual values captured from the URL.
---
`/post/100`
### --feedback--
That is the full path; params only expose the dynamic segment.
---
An empty string
### --feedback--
The placeholder must be filled by the actual value in the URL.
## --video-solution--
1
## --text--
How can you use route parameters in your application?
## --answers--
To store static values in the URL.
### --feedback--
Static values dont benefit from parameter placeholders.
---
To dynamically capture parts of the URL for processing.
---
To validate user input.
### --feedback--
Validation may occur after capturing the value, but the parameter itself captures data.
---
To define headers for requests.
### --feedback--
Route parameters belong to the path and do not define headers.
## --video-solution--
2
@@ -0,0 +1,147 @@
---
id: 69a918332f325a9cb8ffad18
title: What Are Route Handlers?
challengeType: 19
dashedName: what-are-route-handlers
---
# --description--
In Express, **route handlers** (also called route callback functions or controller functions) are functions that define what happens when a client sends a request to a specific route.
A route handler processes the incoming request, performs any necessary logic like querying a database or running calculations, and then sends a response back to the client.
Lets break this down with a simple example (which youve actually been using all along):
```javascript
app.get("/menu", (req, res) => {
res.send("Welcome to the menu!");
});
```
The `.get()` method is one of Expresss route methods. It listens for **GET** requests at a specified route. In this example, it listens for requests to `/menu`.
The function `(req, res) => { ... }` is the **route handler**. It runs whenever a client sends a GET request to `/menu`.
Inside the handler:
* `req` (request) is an object that contains information about the incoming request, such as route parameters, query strings, headers, and body data.
* `res` (response) is an object used to send a response back to the client.
In this case, `res.send("Welcome to the menu!")` sends a plain text response to the client.
When a user navigates to `/menu` in the browser—or sends a GET request to that route—the server executes this handler and responds with the message `Welcome to the menu!`.
Route handlers are the core of an Express application. They allow you to define how different routes of your web application will respond to requests. You can also add logic to these handlers, such as processing form data, interacting with databases, or performing validation.
# --questions--
## --text--
What is a route handler in Express?
## --answers--
A function that handles incoming requests and sends a response.
---
A method to handle GET requests.
### --feedback--
Consider the purpose of the function in the route.
---
A way to define a route URL.
### --feedback--
Consider the purpose of the function in the route.
---
A type of middleware.
### --feedback--
Consider the purpose of the function in the route.
## --video-solution--
1
## --text--
In the code `app.get('/menu', (req, res) => { res.send('Welcome to the menu!') })`, what does the `res.send()` method do?
## --answers--
It defines the route for the `/menu`.
### --feedback--
Think about what happens when the client receives a response.
---
It sends a response back to the client.
---
It processes the incoming request.
### --feedback--
Think about what happens when the client receives a response.
---
It performs a database query.
### --feedback--
Think about what happens when the client receives a response.
## --video-solution--
2
## --text--
What type of request does the `.get()` method in Express listen for?
## --answers--
POST requests
### --feedback--
Consider what HTTP method is being used in this example.
---
PUT requests
### --feedback--
Consider what HTTP method is being used in this example.
---
GET requests
---
DELETE requests
### --feedback--
Consider what HTTP method is being used in this example.
## --video-solution--
3
@@ -0,0 +1,181 @@
---
id: 69a9183588765b5a18d20954
title: What Are the Different Response Methods in Express?
challengeType: 19
dashedName: what-are-the-different-response-methods-in-express
---
# --description--
In Express, the `res` (response) object is used to send responses back to the client after processing incoming requests. Express provides several built-in methods for sending different types of responses. For example, you can send plain text, JSON data, redirect a user to another URL, or render a template.
One of the most commonly used response methods is `res.send()`:
```javascript
app.get("/text", (req, res) => {
res.send("Hello, World!");
});
```
The `res.send()` method sends a response back to the client. It can send plain text, HTML, JSON, or even binary data. In this example, when a client visits `/text`, the server responds with the text `Hello, World!`.
Another commonly used response method is `res.json()`.
This method sends a JSON response to the client. Its especially useful when building APIs, where you often need to return structured data such as objects or arrays. Express automatically converts a JavaScript object into a JSON-formatted string:
```javascript
app.get("/user", (req, res) => {
res.json({ name: "John Doe", age: 30 });
});
```
If a client sends a request to `/user`, the server responds with the following:
```json
{
"name": "John Doe",
"age": 30
}
```
When you need to control the HTTP status code of a response, you can use `res.status()`. This method sets the status code and is typically chained with another response method like `res.send()` or `res.json()`:
```javascript
app.get("/notfound", (req, res) => {
res.status(404).send("Not Found");
});
```
Here, the server sets the status code to `404` and sends the message `Not Found` back to the client.
If you want to send the user to a different URL, you can use `res.redirect()`:
```javascript
app.get("/oldpage", (req, res) => {
res.redirect("/newpage");
});
```
When a client visits `/oldpage`, they are automatically redirected to `/newpage`.
Finally, `res.render()` is used when working with template engines such as Pug, EJS, or Handlebars. It renders a view template and sends the resulting HTML to the client:
```javascript
app.get("/profile", (req, res) => {
res.render("profile", { username: "john_doe" });
});
```
In this example, the server renders a `profile` view and passes a `username` variable to it, which can then be displayed in the HTML.
These response methods allow you to return different types of data based on the nature of the request. Whether you're sending text, JSON data, or redirecting the client, Express has a flexible set of tools to handle it.
# --questions--
## --text--
What does the `res.json()` method do?
## --answers--
Sends a JSON response to the client.
---
Sends plain text to the client.
### --feedback--
Think about the format of the data you're sending back.
---
Sets the status code of the response.
### --feedback--
Think about the format of the data you're sending back.
---
Redirects the client to another URL.
### --feedback--
Think about the format of the data you're sending back.
## --video-solution--
1
## --text--
How would you send a 404 status code with a custom message?
## --answers--
`res.send(404, 'Not Found')`
### --feedback--
What method do you use to set the status code?
---
`res.status(404).send('Not Found')`
---
`res.redirect('/404')`
### --feedback--
What method do you use to set the status code?
---
`res.status(500).send('Error')`
### --feedback--
What method do you use to set the status code?
## --video-solution--
2
## --text--
What does the `res.redirect()` method do?
## --answers--
Sends a file to the client.
### --feedback--
Think about what happens when a URL redirects to another URL.
---
Redirects the client to another URL.
---
Sends JSON data to the client.
### --feedback--
Think about what happens when a URL redirects to another URL.
---
Sets the response status code.
### --feedback--
Think about what happens when a URL redirects to another URL.
## --video-solution--
2
@@ -0,0 +1,175 @@
---
id: 69a918497b6424e132898217
title: How Can You Create Chainable Route Handlers Using app.route()?
challengeType: 19
dashedName: how-can-you-create-chainable-route-handlers-using-approute
---
# --description--
In Express, you can create **chainable route handlers** using the `app.route()` method. This is helpful when you want to handle multiple HTTP methods such as GET, POST, or PUT for the same route path without repeating that path each time.
Instead of writing separate route definitions like `app.get("/user")`, `app.post("/user")`, and `app.put("/user")`, `app.route()` lets you group them together in a single, organized block of code.
The `app.route()` method acts as a shortcut for defining multiple handlers for the same endpoint. This is especially useful in RESTful APIs, where a single resource (like `/user`) often supports several operations.
Heres an example that simulates a RESTful API for managing users:
```javascript
const express = require("express");
const app = express();
const port = 3000;
app.use(express.json()); // Parse JSON request bodies
// Use app.route() to group handlers for the same path
app
.route("/user")
.get((req, res) => {
res.send("Fetching user data");
})
.post((req, res) => {
const { name } = req.body;
res.send(`Creating a user with name: ${name}`);
})
.put((req, res) => {
const { name } = req.body;
res.send(`Updating the user to: ${name}`);
})
.delete((req, res) => {
res.send("Deleting the user");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
```
In the example above, `app.route("/user")` defines a single route for the `/user` path. We then chain multiple HTTP methods, `.get()`, `.post()`, `.put()`, and `.delete()`, to handle different types of requests for that same route.
Heres a breakdown of the different routes and how they might work in a simple RESTful app:
* GET `/user`: Fetches and returns user data.
* POST `/user`: Creates a new user with data in the request body.
* PUT `/user`: Updates an existing user with data in the request body.
* DELETE `/user`: Deletes a user.
Using `app.route()` helps keep your code organized when handling multiple HTTP methods for the same path. Instead of repeating the route each time, you group related handlers together in one place.
This reduces redundancy and makes your code easier to read and maintain. When all the methods for a route are defined in a single block, its much clearer how that endpoint behaves.
As your application grows and routes become more complex, `app.route()` provides a simple structure that keeps related logic together. Its especially useful when designing RESTful APIs, where a single resource often supports multiple operations such as GET, POST, PUT, and DELETE.
# --questions--
## --text--
What is the purpose of using `app.route()` in Express?
## --answers--
To define different HTTP methods for the same route.
---
To create an HTTP server.
### --feedback--
Think about handling multiple HTTP methods for a single resource.
---
To handle static files.
### --feedback--
Think about handling multiple HTTP methods for a single resource.
---
To define routes for different paths.
### --feedback--
Think about handling multiple HTTP methods for a single resource.
## --video-solution--
1
## --text--
Which of the following methods can be chained with `app.route()`?
## --answers--
`.get()`, `.post()`, `.put()`, `.delete()`
---
`.send()`, `.render()`, `.json()`, `.status()`
### --feedback--
Think about how you can handle different types of requests for the same path.
---
`.use()`, `.listen()`, `.next()`, `.static()`
### --feedback--
Think about how you can handle different types of requests for the same path.
---
None of the above
### --feedback--
Think about how you can handle different types of requests for the same path.
## --video-solution--
1
## --text--
Which two HTTP methods typically do not require a request body?
## --answers--
`.get()` and `.delete()`
---
`.get()` and `.post()`
### --feedback--
Consider the type of operation each method is performing on the resource.
---
`.post()` and `.put()`
### --feedback--
Consider the type of operation each method is performing on the resource.
---
`.put()` and `.delete()`
### --feedback--
Consider the type of operation each method is performing on the resource.
## --video-solution--
1
@@ -0,0 +1,208 @@
---
id: 69a9184b42ae3947e4925016
title: How Does express.Router Work?
challengeType: 19
dashedName: how-does-expressrouter-work
---
# --description--
In Express, `express.Router()` is a powerful feature that helps you organize your routes into smaller, modular pieces. This is especially useful as your application grows.
Instead of defining all your routes in one large file, you can split them into separate files using routers. This keeps your code easier to read, maintain, and scale.
The `express.Router()` method creates a new router object.
A router works like a mini Express application. It can handle its own routes and middleware, but it is not a full-fledged Express application. Once you define routes on a router, you can mount it in your main app using `app.use()`.
In other words, a router lets you group related routes together and then later integrate them into your main application.
Using routers has several advantages:
**Separation of concerns**
You can define routes in separate files, which improves the organization and readability of your application.
**Code reusability**
Routers can be reused in different parts of an application or even across projects.
**Cleaner main file**
Instead of filling your main `app.js` or `server.js` file with many route definitions, you can move them into routers and keep your main file focused on configuration and setup.
Lets look at a simple example where we use `express.Router()` to define routes for the `/users` path.
First, here's the `app.js` file:
```javascript
const express = require("express");
const app = express();
const port = 3000;
// Importing the user routes
const userRoutes = require("./userRoutes");
// Using the userRoutes router for /users path
app.use("/users", userRoutes);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
```
And here's `userRoutes.js`:
```javascript
const express = require("express");
const router = express.Router();
// GET request for /users
router.get("/", (req, res) => {
res.send("List of users");
});
// POST request for /users
router.post("/", (req, res) => {
res.send("Creating a new user");
});
// GET request for /users/:id
router.get("/:id", (req, res) => {
const userId = req.params.id;
res.send(`User details for user with id: ${userId}`);
});
module.exports = router;
```
Now let's take a closer look at how everything works.
In `app.js`, we import `express` and create an instance of the Express application and assign it to a variable named `app`.
Next, we import the `userRoutes` router from `userRoutes.js` and use `app.use("/users", userRoutes)` to mount the router. This tells Express that, if a request starts with `/users`, pass it to the `userRoutes` router.
Then in `userRoutes.js`, we create a new router using `express.Router()` and define routes using `router.get()`, `router.post()`, and `router.get("/:id")`.
Note that the routes defined here are relative to `/users` because that's where the router is mounted. So:
* `router.get("/")``GET /users`: Responds with a list of users
* `router.post("/")``POST /users`: Responds with a message about creating a new user
* `router.get("/:id")``GET /users/:id`: Responds with user details for a given user ID
Using `express.Router()` keeps your main file clean and focused on configuration. All user-related routes are grouped together in `userRoutes.js`.
As your application grows, you can create additional routers for other sections, such as `/products`, `/orders`, or `/auth`.
Each section stays organized in its own file, making the application easier to maintain and scale.
# --questions--
## --text--
What does `express.Router()` do?
## --answers--
Creates a new instance of the Express application.
### --feedback--
Think about modularizing routes in your app.
---
Defines middleware for a specific route.
### --feedback--
Think about modularizing routes in your app.
---
Creates a router object for handling routes.
---
Starts the server.
### --feedback--
Think about modularizing routes in your app.
## --video-solution--
3
## --text--
How do you integrate a router into the main app?
## --answers--
By calling `app.use()` and passing the router.
---
By calling `app.get()` directly inside the router.
### --feedback--
Consider how the `app.js` uses the router to handle `/users` requests.
---
By using `router.listen()`.
### --feedback--
Consider how the `app.js` uses the router to handle `/users` requests.
---
By importing the router and calling `router.start()`.
### --feedback--
Consider how the `app.js` uses the router to handle `/users` requests.
## --video-solution--
1
## --text--
What is the benefit of using `express.Router()`?
## --answers--
It helps you handle static files.
### --feedback--
Think about how routers help organize code for large applications.
---
It allows you to group route handlers and apply middleware to specific paths.
---
It enables you to handle the database connection.
### --feedback--
Think about how routers help organize code for large applications.
---
It automatically starts the Express server.
### --feedback--
Think about how routers help organize code for large applications.
## --video-solution--
2
@@ -0,0 +1,211 @@
---
id: 69a9184df26779d958824552
title: How Can You Serve Static Files in Express?
challengeType: 19
dashedName: how-can-you-serve-static-files-in-express
---
# --description--
Serving static files is a common requirement in web applications. Static files include assets like images, CSS files, client-side JavaScript, fonts, and other resources that do not change dynamically.
Express makes serving these files simple with its built-in `express.static()` middleware.
In Express, static file serving means delivering files directly from the servers file system to the clients browser without any additional server-side processing.
For example, when a browser requests files like `/styles.css`, `/script.js`, or `/images/logo.png`, Express can locate those files in a specified folder and serve them directly. If a file isn't found, then Express will respond automatically with a 404. Since these files dont need to be generated or modified on the server, they are called *static*.
This makes serving assets like stylesheets and images easy, and removes the need to manually define routes for each file.
Heres how you can set up static file serving in Express:
```javascript
const express = require("express");
const path = require("path");
const app = express();
const port = 3000;
// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => {
res.send("Welcome to the static file demo!");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
```
First, we import `express` to create our server and `path` to safely construct file paths across different operating systems.
Next, `app.use(express.static(path.join(__dirname, "public")))` tells Express to serve files from the `public` folder. The `express.static()` middleware tells Express to serve files from the `public` folder. Any file inside this directory becomes accessible to the browser.
We also define a simple `GET` route for `/` that sends a welcome message. This shows that static file serving can coexist with dynamic routes.
Finally, `app.listen()` starts the server on port 3000. Once the server is running, requests for static assets in the `public` folder are handled automatically.
For this to work, you need a folder named `public` to store your static files. A typical project structure might look like this:
```md
my-app/
├── app.js
└── public/
├── index.html
├── styles.css
└── image.png
```
When a user makes a request, for example, by visiting `http://localhost:3000/index.html`, Express checks whether the requested file exists inside the `public` directory. If the file exists, Express sends it directly to the browser. If the file does not exist, Express moves on to the next middleware or returns a 404 response.
Remember that you don't need to define routes for each file, so a request to `http://localhost:3000/styles.css` means that Express looks for the `public/styles.css` and responds with it automatically.
You can also customize how static files are served. For example, you might serve files from multiple directories or configure caching behavior.
Imagine your app has this file structure:
```md
my-app/
├── app.js
├── public/
│ ├── index.html
│ └── styles.css
└── images/
└── image.png
```
Here's how you can register multiple directories to serve static files from:
```javascript
app.use(express.static(path.join(__dirname, "public")));
app.use("/images", express.static(path.join(__dirname, "images")));
```
Here we use `app.use(express.static(path.join(__dirname, "public")));` just like before, which means that files inside the `public` directory are served from the root path, just like before.
But if you look at the next line, you'll see we pass `"/images"` as the first argument to `app.use()`, followed by `express.static(path.join(__dirname, "images"))`. In this case, `"/images"` is a mount path, which tells Express to only use this middleware when it receives a request to `/images`. When it does, `express.static()` triggers and looks for files inside the `images` directory.
So with this configuration, here's how the following requests would work:
* GET `http://localhost:3000/styles.css`: Express looks in the `public` directory for `styles.css`, finds the file, and sends it to the client.
* GET `http://localhost:3000/images/image.png`: Since this request starts with `/images`, Express looks in the `images` directory for `image.png`, finds the file, and sends it to the client.
Serving static files with Express is simple and powerful. By using `express.static()`, you can easily serve assets like images, stylesheets, and client-side JavaScript.
Keeping static files in a dedicated folder like `public`, or by using multiple file directories and mount paths, helps keep your application organized, maintainable, and easy to scale.
# --questions--
## --text--
What does `express.static()` do?
## --answers--
It creates a new Express application.
### --feedback--
Think about how static files are handled in Express.
---
It serves static files from a specified directory.
---
It defines the port number for the server.
### --feedback--
Think about how static files are handled in Express.
---
It logs requests made to the server.
### --feedback--
Think about how static files are handled in Express.
## --video-solution--
2
## --text--
Where should you place your static files in order for them to be served by Express?
## --answers--
In the root directory of the app.
### --feedback--
Consider common practices for organizing static assets.
---
In the `public` folder.
---
In the `views` folder.
### --feedback--
Consider common practices for organizing static assets.
---
In the `node_modules` folder.
### --feedback--
Consider common practices for organizing static assets.
## --video-solution--
2
## --text--
What happens when a user requests `/index.html` on a server that uses `express.static()` to serve static files from the `public` folder?
## --answers--
The server will display an error page.
### --feedback--
Think about how Express serves files from a directory.
---
The server will look for `public/index.html` and serve it.
---
The server will redirect the user to another page.
### --feedback--
Think about how Express serves files from a directory.
---
The server will send a 404 error code.
### --feedback--
Think about how Express serves files from a directory.
## --video-solution--
2
@@ -0,0 +1,41 @@
{
"isUpcomingChange": true,
"dashedName": "lecture-understanding-routing-in-express-js",
"helpCategory": "Backend Development",
"blockLayout": "challenge-list",
"challengeOrder": [
{
"id": "69a848d4f1d1b4b9e176a026",
"title": "What Is Routing and How Do Route Methods Work in Express?"
},
{
"id": "69a9182c1bc7cc1a76116635",
"title": "What Are Route Paths in Express?"
},
{
"id": "69a91831ef910efdde054a5a",
"title": "What Are Route Parameters?"
},
{
"id": "69a918332f325a9cb8ffad18",
"title": "What Are Route Handlers?"
},
{
"id": "69a9183588765b5a18d20954",
"title": "What Are the Different Response Methods in Express?"
},
{
"id": "69a918497b6424e132898217",
"title": "How Can You Create Chainable Route Handlers Using app.route()?"
},
{
"id": "69a9184b42ae3947e4925016",
"title": "How Does express.Router Work?"
},
{
"id": "69a9184df26779d958824552",
"title": "How Can You Serve Static Files in Express?"
}
],
"blockLabel": "lecture"
}
@@ -50,7 +50,8 @@
"comingSoon": true,
"blocks": [
"lecture-understanding-rest-api-and-web-services",
"lecture-working-with-express"
"lecture-working-with-express",
"lecture-understanding-routing-in-express-js"
]
},
{