0
0
Expressframework~30 mins

Dependency injection in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Dependency Injection in Express
📖 Scenario: You are building a simple Express server that needs to use a service for greeting users. To keep your code clean and testable, you will use dependency injection to provide the greeting service to your route handler.
🎯 Goal: Create an Express app that uses dependency injection to pass a greeting service to a route handler. The app will respond with a greeting message when a user visits the /greet endpoint.
📋 What You'll Learn
Create a greeting service function that returns a greeting string.
Create a configuration variable for the greeting message prefix.
Inject the greeting service into the Express route handler.
Set up the Express app to listen on port 3000.
💡 Why This Matters
🌍 Real World
Dependency injection helps keep Express apps modular and testable by separating service logic from route handlers.
💼 Career
Understanding dependency injection is important for writing clean, maintainable backend code in Node.js and Express, a common skill in web development jobs.
Progress0 / 4 steps
1
Create the greeting service function
Create a function called greetingService that takes a name parameter and returns the string `Hello, ${name}!`.
Express
Need a hint?

Define a function that uses a template string to return a greeting.

2
Create a greeting prefix configuration variable
Create a constant called greetingPrefix and set it to the string 'Hello'.
Express
Need a hint?

Create a constant variable to hold the greeting prefix string.

3
Inject the greeting service into the Express route handler
Create an Express app by requiring express and calling express(). Then create a route handler for /greet that uses the injected greetingService to send a greeting for the query parameter name. Use req.query.name to get the name.
Express
Need a hint?

Use express() to create the app and define a GET route for /greet. Use the greeting service inside the route.

4
Start the Express server on port 3000
Add code to make the Express app listen on port 3000 using app.listen.
Express
Need a hint?

Use app.listen(3000) to start the server on port 3000.