Complete the code to create a new Express router.
const express = require('express'); const router = express.[1]();
Use express.Router() to create a new router instance.
Complete the code to define a GET route for '/users' that sends a JSON response.
router.[1]('/users', (req, res) => { res.json({ message: 'List of users' }); });
The GET method is used to retrieve data, so use router.get() for this route.
Fix the error in the route path to correctly capture a user ID parameter.
router.get('/users/[1]', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); });
Route parameters start with a colon and the name must match the code accessing req.params.id. So use :id.
Fill both blanks to export the router and import it in the main app file.
// In routes/users.js const express = require('express'); const router = express.Router(); // ... define routes ... module.exports = [1]; // In app.js const express = require('express'); const app = express(); const usersRouter = require('./routes/users'); app.use('/users', [2]);
Export the router as router and import it as usersRouter in the main app, then use app.use('/users', usersRouter).
Fill all three blanks to create a resource-based route for posts with GET, POST, and DELETE methods.
const express = require('express'); const router = express.Router(); router.[1]('/posts', (req, res) => { res.send('Get all posts'); }); router.[2]('/posts', (req, res) => { res.send('Create a post'); }); router.[3]('/posts/:id', (req, res) => { res.send(`Delete post ${req.params.id}`); });
Use get to retrieve posts, post to create a post, and delete to remove a post by ID.