Express.js | (Backend Pt.2)
I am a MERN developer, I have made several projects using this tech stack, also, I am a ML enthusiast currently I am learning about different python libraries that we use in data science. Along with that I am also trying to contribute in open-source projects using all the tech stacks and skills that I have mentioned above.
What is express?
Let's start with the most basic question, what is express?
Express.js, commonly referred to as Express, is a minimal and flexible web application framework for Node.js. It provides a robust set of features and tools for building web and mobile applications, primarily for creating server-side applications and APIs (Application Programming Interfaces).
What is a framework?
A framework is a structured and organized set of tools, libraries, guidelines, and conventions that developers use to create and maintain software applications. It provides a foundation for building applications by offering pre-written and reusable code, which helps developers solve common problems and tasks more efficiently.
Creating server
import express from "express";
const app = express();
app.listen(3000, () => {
console.log("Server is running on port 3000")
} )

Routing
In Express.js, routing refers to the mechanism by which your application responds to different HTTP requests. You define routes to handle specific URLs (or patterns of URLs) and specify the logic that should be executed when a request matches a particular route. Here's a basic overview of routing in Express.js:
import express from "express";
const app = express();
app.get("/", function(req, res) {
res.send("Hey there I am the home page");
})
app.get("/profile", function(req, res){
res.send("Hey you are on the profile page");
})
app.listen(3000, () => {
console.log("Server is running on port 3000")
} )

When we add the URL "/profile" with the base URL we can see the content we have written in that route.
Middleware
When you want to render something before anything like in this case routing you can use Middleware for that.
In Express.js, middleware runs in the order in which it is defined, and it runs before the route handler for a specific route. The middleware functions are executed in the order they appear in your code, and they have access to the request and response objects.
import express from "express";
const app = express();
app.use(function(req, res, next){
console.log("Hey I am using middleware");
})
app.get("/", function(req, res) {
res.send("Hey there I am the home page");
})
app.get("/profile", function(req, res){
res.send("Hey you are on the profile page");
})
app.listen(3000, () => {
console.log("Server is running on port 3000")
} )

As we can see Middleware runs first and the routing part is getting done.



