Step 2
Adding a router
Let's create a router
Inside the "src" folder, create a folder called "routes", and inside of that, create a file called "books.js"
Inside "books.js", let's add some logic for handling an HTTP request.
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Here are the books');
});
module.exports = router;
Here, we are creating a router, an independent HTTP request handler. For this route, we will handle any HTTP GET request to any URL ending with, "/", by responding with "Here are the books". Finally, we export the router with all of the logic for handling requests wired up.
This does not do anything yet, so we need to register our router with our Express app.
const express = require('express');
const books = require('./routes/books');
const PORT = process.env.PORT || 5000;
const app = express();
app.use('/api/books', books);
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`);
});
We first import our books router and then register it on line 7. What this means is that we are registering our router to be used on the route "/api/books", so when we make an HTTP GET request to "localhost:5000/api/books/", then we will get the response, "Here are the books"
Last updated
Was this helpful?