Router()
and RESTful API
Demonstrating Express.js Live Code
Router()
routes
Step 1 - Scaffold - Create a
routes.js
file - Demonstrate creating a new Express app instance and prompt students:
- What would be wrong with initializing a new application?
const express = require('express') const app = express()
- Introduce
Router()
- A
router
object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.
const router = require('express').Router()
- A
- Copy and paste all of the routes from the
app.js
file- Update
app
torouter
- Update
- Export the router
module.exports = router
app.js
Step 2 - Refactor - Near the top of the
app.js
file, import in the routes usingrequire
const routes = require('./routes.js')
- Use the routes
app.use(routes)
- For further granularity, we can break the routes file into two separate files. In this case, we would have to require them both in then.
countriesRouter.js
citiesRouter.js
app.use('/countries', require('./countriesRouter.js')) app.use('/cities', require('./citiesRouter.js'))
Step 3 - Using body-parsing middleware
POST
requests/routes are designated for creating something. For example, let's say we want to create a newcity
. We can send some data to do so in our HTTP request message in a couple of ways:- Form data (URL encoded) is sent as strings or arrays, which we must use Express'
app.use(express.urlencoded({ extended: false }))
to parse easily. - JSON object, which we must use Express'
app.use(express.json())
to parse easily.
- Form data (URL encoded) is sent as strings or arrays, which we must use Express'
- Demonstrate using Postman