Complete the code to start an Express server listening on port 3000.
const express = require('express'); const app = express(); app.listen([1], () => { console.log('Server running'); });
The listen method needs a number for the port. Using 3000 starts the server on port 3000.
Complete the code to add a middleware that parses JSON bodies in requests.
const express = require('express'); const app = express(); app.use([1]());
Express has a built-in middleware called express.json() to parse JSON request bodies.
Fix the error in the code to properly handle errors in Express.
app.use((err, req, res, [1]) => { console.error(err.stack); res.status(500).send('Something broke!'); });
The error-handling middleware in Express must have four arguments: err, req, res, next. The last one is next.
Fill both blanks to create a route that responds with JSON and sets a custom header.
app.get('/info', (req, res) => { res.set('[1]', '[2]').json({ message: 'Hello' }); });
To add a custom header, use res.set('X-Custom-Header', 'CustomValue'). The JSON response is sent after setting the header.
Fill all three blanks to create a middleware that logs request method, URL, and then calls next.
app.use(([1], [2], [3]) => { console.log(`$[1].method} $[2].url}`); [3](); });
Middleware functions receive req, res, and next. We log req.method and req.url, then call next() to continue.