Complete the code to create a basic Express server.
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen([1], () => { console.log('Server is running'); });
The listen method needs a port number as a number, not a string or other value.
Complete the code to add middleware that logs request method and URL.
app.use((req, res, next) => {
console.log(req.[1] + ' ' + req.url);
next();
});req.path instead of req.method.req.body without parsing middleware.The method property of the request object tells us the HTTP method like GET or POST.
Fix the error in the route handler to send JSON response.
app.get('/data', (req, res) => { res.[1]({ message: 'Hello JSON' }); });
sendFile when sending JSON data.render without a view engine.The json method sends a JSON response properly formatted.
Fill both blanks to create a route that handles POST requests and parses JSON body.
app.[1]('/submit', (req, res) => { const data = req.[2]; res.json({ received: data }); });
get instead of post for POST routes.req.query instead of req.body.Use post to handle POST requests and req.body to access parsed JSON data.
Fill all three blanks to create a modular router and use it in the main app.
const express = require('express'); const app = express(); const router = express.Router(); router.[1]('/info', (req, res) => { res.json({ info: 'Router info' }); }); app.[2]('/api', router); app.listen([3], () => { console.log('Server running'); });
post instead of get for the router route.app.get instead of app.use to mount router.listen.Use get to define a GET route on the router, use to mount the router on the app, and a port number like 3001 to listen.
