0
0
Expressframework~10 mins

Dependency injection in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import Express and create an app instance.

Express
const express = require('[1]');
const app = express();
Drag options to blanks, or click blank then click option'
Apath
Bhttp
Cfs
Dexpress
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'http' instead of 'express' to import Express.
Forgetting to require the module before using it.
2fill in blank
medium

Complete the code to inject a dependency into a route handler using Express's request object.

Express
app.get('/greet', (req, res) => {
  const greeter = req.[1].greeter;
  res.send(greeter.greet());
});
Drag options to blanks, or click blank then click option'
Aparams
Bbody
Ccontainer
Dquery
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'req.body' which holds POST data, not dependencies.
Using 'req.params' or 'req.query' which hold URL parameters.
3fill in blank
hard

Fix the error in the middleware that injects a service into the request object.

Express
function injectService(req, res, next) {
  req.[1] = { greeter: { greet: () => 'Hello!' } };
  next();
}
Drag options to blanks, or click blank then click option'
Acontainer
Binject
Cservices
Dservice
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent property names causing undefined errors.
Not calling next() to pass control to the next middleware.
4fill in blank
hard

Fill both blanks to create middleware that injects a logger service and use it in a route.

Express
function injectLogger(req, res, next) {
  req.[1] = { log: (msg) => console.log(msg) };
  next();
}

app.get('/log', (req, res) => {
  req.[2].log('Logging a message');
  res.send('Logged');
});
Drag options to blanks, or click blank then click option'
Acontainer
Bservices
Clogger
Dinject
Attempts:
3 left
💡 Hint
Common Mistakes
Using different property names in middleware and route causing undefined errors.
Forgetting to call next() in middleware.
5fill in blank
hard

Fill all three blanks to define a service, inject it via middleware, and use it in a route.

Express
const greeterService = {
  greet: () => '[1]'
};

function injectServices(req, res, next) {
  req.[2] = { greeter: greeterService };
  next();
}

app.get('/hello', (req, res) => {
  res.send(req.[3].greeter.greet());
});
Drag options to blanks, or click blank then click option'
AHello, friend!
Bcontainer
Dservices
Attempts:
3 left
💡 Hint
Common Mistakes
Using different property names for injection and access.
Returning the wrong greeting string.