Express is a popular framework in Node.js. What is its main purpose?
Think about what web servers do and how Express helps with that.
Express is a minimal and flexible Node.js web application framework that provides tools to build web servers and APIs. It simplifies handling HTTP requests and responses.
Consider this Express app code. What will a user see when they visit the root URL '/'?
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.send('Hello from Express!'); }); app.listen(3000);
Look at the route defined with app.get and what it sends back.
The app listens for GET requests at '/' and responds with the text 'Hello from Express!'. So visiting '/' shows that text.
Choose the code snippet that correctly creates an Express app and starts the server on port 4000 without errors.
Remember to call the express function to create the app and use correct import syntax for ES modules.
Option B uses ES module import syntax and calls express() to create the app. It also provides a callback to listen(). Options C and D forget to call express() as a function. Option B uses CommonJS require which may not work if ES modules are expected.
Look at this code snippet. Why does it crash with the error 'TypeError: app.get is not a function'?
import express from 'express'; const app = express(); app.get('/', (req, res) => res.send('Hi')); app.listen(3000);
Check how the app variable is assigned from express.
The code assigns 'app = express' instead of 'app = express()'. Without calling express(), app is just a reference to the function, not an Express app instance. So app.get is undefined.
Given this Express app with middleware, what will the client see when requesting '/'?
import express from 'express'; const app = express(); app.use((req, res, next) => { req.message = 'Hello'; next(); }); app.use((req, res, next) => { req.message += ' from middleware'; next(); }); app.get('/', (req, res) => { res.send(req.message); }); app.listen(3000);
Think about how middleware modifies the request object before the route handler runs.
The first middleware sets req.message to 'Hello'. The second appends ' from middleware'. The route sends req.message, so the output is 'Hello from middleware'.