express.js router example
The express app can create get, post, put and delete url endpoints directly by invoking app.get(), app.post(), app.put() and app.delete(). Each of these function takes two parameters, the first is a url path and the second is a function to handle the request. Whenever these functions are invoked with a new url path, it is added to a global array that holds these url paths. When a request comes in, it look up the incoming url path in this global array in order to direct the request to the appropriate handler. When an application has a lot of url endpoints and all those are saved in the global array of url paths, the url path look up time will increase as more and more endpoints are being added. To reduce the look up time, we can avoid adding the endpoint url path to the global app. Instead, each module can have its own router and that router can be added to the global app as a middleware.
app.js, The first 3 lines create express app, include read and update router modules that will be created in the following. The next 3 iines uses the read and update router as a middleware in the express app object, and listen to port 3000. The root url path for readRouter and updateRouter will be localhost:3000/read/ and localhost:3000/update/ respectively. The last line just prints a comment when the app started.
var app = require("express")(); var readRounter = require("./read"); var updateRouter = require("./update"); app.use("/read", readRounter); app.use("/update", updateRouter); app.listen(3000); console.log("App running at localhost:3000");
read.js, the first line creates a router from express’s Router() function. The two functions are handling the get requests. The router has a get function which takes two parameters, the first is an url path and the second is a function to handle the request.
var router = require("express").Router(); function getName(req, res) { res.send("Amy"); } function getEmail(req, res) { res.send("amy@test.com"); } router.get("/name", getName); router.get("/email", getEmail); module.exports = router;
update.js, the first line creates a router from express’s Router() function. The two functions are handling the post requests. The router has a post function which takes two parameters, the first is an url path and the second is a function to handle the request.
var router = require("express").Router(); function updateName(req, res) { //TODO update name res.send("Name updated!"); } function updateEmail(req, res) { //TODO update email res.send("Email updated!"); } router.post("/name", updateName); router.post("/email", updateEmail); module.exports = router;
Install, start and use the app from command line
sudo npm install express node app.js & curl localhost:3000/read/name curl localhost:3000/read/email curl -X POST localhost:3000/update/name curl -X POST localhost:3000/update/email
Output:
Amy amy@test.com Name updated! Email updated!
Search within Codexpedia
Search the entire web