Complete the code to create a basic Express server that listens on port 3000.
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen([1], () => { console.log('Server running'); });
The standard port for local Express servers is often 3000. This code starts the server on port 3000.
Complete the code to add middleware that parses JSON bodies in Express.
const express = require('express'); const app = express(); app.use([1]()); app.post('/data', (req, res) => { res.json(req.body); });
Express has built-in middleware called express.json() to parse JSON request bodies.
Fix the error in the route handler to correctly send a JSON response.
app.get('/user', (req, res) => { res.[1]({ name: 'Alice' }); });
To send a JSON response, use res.json() in Express.
Fill both blanks to create a route that handles URL parameters and sends them back.
app.get('/user/:[1]', (req, res) => { const [2] = req.params.id; res.send(`User ID is ${id}`); });
The URL parameter is named 'id', so req.params.id accesses it. The variable to hold it should be 'id' to match the template string.
Fill all three blanks to create a middleware that logs request method and URL, then passes control.
function logger(req, res, [1]) { console.log(`${req.method} ${req.[2]`); [3](); } app.use(logger);
The third parameter in middleware is 'next' to pass control. The URL is accessed via req.url. Calling next() continues to the next middleware.