Complete the code to import Express and create an app instance.
const express = require('[1]'); const app = express();
The Express library is imported by requiring 'express'. This creates the Express module needed to create the app.
Complete the code to inject a dependency into a route handler using Express's request object.
app.get('/greet', (req, res) => { const greeter = req.[1].greeter; res.send(greeter.greet()); });
Dependency injection can be done by attaching dependencies to a custom property on the request object, often named 'container' or similar.
Fix the error in the middleware that injects a service into the request object.
function injectService(req, res, next) {
req.[1] = { greeter: { greet: () => 'Hello!' } };
next();
}Using 'req.container' is a common pattern to hold injected dependencies in Express middleware.
Fill both blanks to create middleware that injects a logger service and use it in a route.
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');
});Both middleware and route handler use 'req.container' to access injected services consistently.
Fill all three blanks to define a service, inject it via middleware, and use it in a route.
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());
});The service returns a greeting string. Middleware injects it into 'req.container'. The route reads from 'req.container' to call the greet method.