Step 2
The index.js
file for the YouNote API contains several routing methods related to CRUD operations for notes. It is perceivable that we will have other resources/entities, such as users, in this application. It will likely be the case that we will need several other routing methods for CRUD operations for other resources.
Express has a Router object that enables you to move routing logic into a separate file. We will use the express router to refactor routing code.
Create a folder routes
inside the younote-api
folder. The files in this folder will contain all of our routes and we will export them using the express router.
Create a file notes.js
inside routes
folder. Copy and paste the content of index.js
into notes.js
. We will now make the following updates:
-
Remove the following statements
- const port = 4567; - app.use(express.json()); - app.listen(port, () => { - console.log(`Server is listening on http://localhost:${port}`); - });
-
Update the path to
NoteDao
- const NoteDao = require("./model/NoteDao.js"); + const NoteDao = require("../model/NoteDao.js");
-
Make the following update
- const app = express(); + const app = express.Router();
The
Router()
returns an an object with similar HTTP methods (.get
,.post
,.put
,.delete
, etc) to theapp
object we have previously been using. -
Rename
app
variable torouter
(you must apply this consistently to all instances ofapp
innote.js
file). This renaming is not a "must"; it is a good name choice though. -
Add the following statement to the end of
note.js
filemodule.exports = router;
-
Update
index.js
to simply contain the following:const express = require("express"); const noteRoutes = require("./routes/notes.js"); const app = express(); const port = process.env.PORT || 4567; app.use(express.json()); app.use(noteRoutes); app.listen(port, () => { console.log(`Server is listening on http://localhost:${port}`); });
The routes related to "notes" are now encapsulated within
noteRoutes
object and the expressapp
is told to "use" it. Notice that I've also updated the declaration ofport
with somewhat forward thinking for when we deploy this application on Heroku.
Run the API server and run the API requests in Postman to ensure this refactoring has not broken our API's behavior.