/hello?import express from 'express'; import helmet from 'helmet'; const app = express(); app.use(helmet()); app.get('/hello', (req, res) => { res.send('Hello World!'); }); app.listen(3000);
The helmet() middleware adds security-related HTTP headers to all responses. Since it is used before the route handler, the response to /hello will include these headers along with the 'Hello World!' message.
When using ES modules, you import the 'cors' package and call it as a function to get the middleware. Then you pass that middleware to app.use(). Option B correctly does this.
/submit?import express from 'express'; const app = express(); app.use('/get', (req, res, next) => { console.log('Middleware triggered'); next(); }); app.post('/submit', (req, res) => { res.send('Submitted'); }); app.listen(3000);
The middleware is registered only for paths starting with '/get'. Since the POST request is to '/submit', the middleware does not run.
/test?import express from 'express'; const app = express(); app.use((req, res, next) => { console.log('First middleware'); next(); }); app.use((req, res, next) => { console.log('Second middleware'); next(); }); app.get('/test', (req, res) => { console.log('Route handler'); res.send('Done'); }); app.listen(3000);
Express executes middleware in the order they are registered. Both middleware call next() to pass control. Finally, the route handler runs.
Middleware can modify req and res objects and decide whether to pass control to the next middleware or end the response. They can be asynchronous. Once a response is sent, next middleware does not run automatically.