0
0
Expressframework~30 mins

Virtual path prefixes in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Virtual Path Prefixes in Express
📖 Scenario: You are building a simple Express server that serves static files and API routes. You want to organize your routes so that all API endpoints start with /api and static files are served under /static. This helps keep your URLs clean and organized.
🎯 Goal: Create an Express server that uses virtual path prefixes to serve static files under /static and API routes under /api. The server should respond with JSON data for the API and serve static HTML files from a folder.
📋 What You'll Learn
Create an Express app instance named app
Serve static files from a folder named public under the virtual path prefix /static
Create a router named apiRouter for API routes
Mount apiRouter on the virtual path prefix /api
Add a GET route /users on apiRouter that returns JSON with a list of users
💡 Why This Matters
🌍 Real World
Virtual path prefixes help organize URLs in web servers. For example, all API calls can be grouped under '/api', and static assets like images or stylesheets can be served under '/static'. This makes the server easier to maintain and the URLs clearer for users.
💼 Career
Understanding how to use virtual path prefixes in Express is essential for backend developers building REST APIs and serving static content. It is a common pattern in real-world web applications to keep routes organized and scalable.
Progress0 / 4 steps
1
Create Express app and static folder setup
Create an Express app instance called app by requiring express and calling it. Then use app.use to serve static files from the folder public under the virtual path prefix /static.
Express
Need a hint?

Use express.static('public') inside app.use with the path prefix /static.

2
Create API router and mount it
Create a router called apiRouter by calling express.Router(). Then mount apiRouter on the app with the virtual path prefix /api using app.use.
Express
Need a hint?

Use express.Router() to create apiRouter and then mount it with app.use('/api', apiRouter).

3
Add GET /users route to apiRouter
Add a GET route /users on apiRouter that sends a JSON response with a key users and value as an array of strings: ["Alice", "Bob", "Charlie"].
Express
Need a hint?

Use apiRouter.get('/users', (req, res) => { res.json(...) }) to send the JSON response.

4
Start the server on port 3000
Add code to start the Express server by calling app.listen on port 3000. Use an arrow function as the callback that does nothing (empty function).
Express
Need a hint?

Use app.listen(3000, () => {}) to start the server.