Member-only story
Node.js Basics — Handle Complex HTTP Requests
Node.js is a popular runtime platform to create programs that run on it.
It lets us run JavaScript outside the browser.
In this article, we’ll look at how to start using Node.js to create programs.
Complex Routing
It’s easy to do simple routing with our own code with our own HTTP server, but if we want to add more complex routing, then we can use the router
module to help us do this.
To use it, we install the router
and finalhandler
packages by running:
npm i router finalhandler
to install the packages.
Then we can use it to handle requests by writing:
const finalhandler = require('finalhandler')
const http = require('http')
const Router = require('router')const router = Router()
router.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('Hello World!')
})const server = http.createServer((req, res) => {
router(req, res, finalhandler(req, res))
})server.listen(8080)
We create the Router
instance and then call the get
method on it to create a GET route to let us handle GET requests to the /
route.