You might be familiar with routes if you've worked with node. Routes help us to organize our app in terms of separate modules. The bigger the app gets the more the number of routes, but then that's where the magic of EXPRESS comes in play.
What is express?
Express.js, or simply Express, is a back end web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs.
Express provides you with a bundle of functions that help you to organize your code better and to focus more on what to do rather than worrying about how it's being done, that's the magic of all frameworks right?
So let's begin by writing our first ever express app and see how we can use the power of Express Router to organize and maintain our code better.
Let us take a scenario where we're building an e-commerce app and write APIs for it.
- Our main file
index.js
const express = require('express')
const app = express()
app.use(express.json())
//Products
let idCounter = 3
const products=[
{
id: 1,
name: "Jeans",
price: "5000",
},
{
id: 2,
name: "Tee",
price: "2500",
}
]
app.get("/", (req,res)=>{
res.send("Hello World!")
})
app.get("/products", (req,res)=>{
res.json(products)
})
app.post("/products", (req,res)=>{
const {name, price} = req.body
const product = {id: idCounter++, name, body}
products.push(product)
res.json({products, success: true})
})
app.listen(3000, (req,res)=>{
console.log("Hey! The server is on!")
})
Using the above route will fetch you the data you have in your products array in JSON form.
It looks simple at the moment right? Yeah now imagine different modules of your apps such as wish list, cart, users and what not. Don't you think you're in for a nightmare while routing everything in such a way that they are as simple as possible and easy to understand but are still getting very complicated to remember?
That's where the magic of Express comes into play. With Express Routes you can organize your code in such a manner, where the routes can be as simple as possible and very easy to remember.
Let's take a look at how we achieve that.
Considering the products module as an example:
- We first create another file named
product.router.js
const express = require('express')
const Router = express.Router()
Router.get("/",(req,res)=>{
res.json({success: true}) //For testing
})
module.exports = router
- making changes in our
index.js
const express = require('express')
const app = express()
const products = require ('product.router.js') // Importing router
app.use(express.json())
app.use("/products", products)
//Products
let idCounter = 3
const products=[
{
id: 1,
name: "Jeans",
price: "5000",
},
{
id: 2,
name: "Tee",
price: "2500",
}
]
app.get("/", (req,res)=>{
res.send("Hello World!")
})
app.get("/products", (req,res)=>{
res.json(products)
})
app.post("/products", (req,res)=>{
const {name, price} = req.body
const product = {id: idCounter++, name, body}
products.push(product)
res.json({products, success: true})
})
app.listen(3000, (req,res)=>{
console.log("Hey! The server is on!")
})
What actually happens when we import and use our router is :
The "/products" path is actually triggering our router and inside our router "/products" route is defined directly by "/"
Hence when you have further paths such as "/products/:id", this will be defined in our product router as "/:id".
This is a relatively small app as of now but you will realize it's importance once you reach a stage where you have to add a large number of routes.
Lets now make the final changes in our product.router.js
and index.js
- index.js
const express = require('express')
const app = express()
const products = require ('product.router.js') // Importing router
app.use(express.json())
app.use("/products", products)
app.get("/", (req,res)=>{
res.send("Hello World!")
})
app.listen(3000, (req,res)=>{
console.log("Hey! The server is on!")
})
- product.router.js
const express = require('express')
const Router = express.Router()
//Products
let idCounter = 3
const products=[
{
id: 1,
name: "Jeans",
price: "5000",
},
{
id: 2,
name: "Tee",
price: "2500",
}
]
Router.get("/",(req,res)=>{
res.json(products)
})
Router.post("/", (req,res)=>{
const {name, price} = req.body
const product = {id: idCounter++, name, body}
products.push(product)
res.json({products, success: true})
})
module.exports = router
Now you can see how organized the code looks with the routes related to "products" all merged into a separate file.
But wait that's not it, Express gives you some more advantage in this. What's that?
Well instead of separately defining "Route.get" and "Route.post" for the same route "/" we can tweak the code some more, here's how:
- product.router.js
const express = require('express')
const Router = express.Router()
//Products
let idCounter = 3
const products=[
{
id: 1,
name: "Jeans",
price: "5000",
},
{
id: 2,
name: "Tee",
price: "2500",
}
]
Router.Route("/") //Notice how the syntax has changed here
.get((req,res)=>{
res.json(products)
})
.post((req,res)=>{
const {name, price} = req.body
const product = {id: idCounter++, name, body}
products.push(product)
res.json({products, success: true})
})
module.exports = router
Did you see how we used "Router.route("/")" and then placed and get and post just below it for the same path.
Hope you found this useful for your projects and do follow me on LinkedIn to get updates on my future blogs :)
Top comments (0)