Consider this Express middleware function:
app.use((req, res, next) => {
console.log(req.method);
next();
});What will be printed when a GET request is made to the server?
const express = require('express'); const app = express(); app.use((req, res, next) => { console.log(req.method); next(); }); app.get('/', (req, res) => { res.send('Hello'); }); app.listen(3000);
Look at the request method property logged.
The middleware logs the HTTP method of the incoming request. For a GET request, it prints 'GET'.
Which option correctly creates an Express app and starts a server using Node.js HTTP module?
const express = require('express'); const http = require('http'); const app = express();
Express apps can be passed as request listeners to Node.js HTTP servers.
Option B correctly passes the Express app as the request handler to http.createServer and then listens on port 3000.
Given this code, why does the server not respond to requests?
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hi');
});
// Missing app.listen callconst express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hi'); });
Check if the server is actually listening for requests.
Without calling app.listen, the Express app does not start a server and cannot respond to requests.
What will be the response body when a client requests '/'?
const express = require('express'); const http = require('http'); const app = express(); app.get('/', (req, res) => { res.send('Welcome'); }); const server = http.createServer(app); server.listen(3000);
Express app can be used as a request handler for Node.js HTTP server.
The HTTP server forwards requests to the Express app which sends 'Welcome' for '/' route.
Which statement best describes how Express builds on Node.js HTTP module?
Think about how Express adds convenience methods to the request and response.
Express extends the native Node.js HTTP objects by adding useful methods and properties to simplify handling requests and responses.