Creating Routes and Handling Requests with Express
Express is one of the most popular framework when we comes to backend side build on top of node.js.
What is express ?
Express is framework built on top of node.js when it comes with node.js + express provide a insane speed of development building APIs. Express is a minimalist, flexible and unopinionated. There is not any file structure in express like Django or other framework.
Why express simplifies node.js development?
- Express make easy to create APIs simple way to define how application response to client on HTTP methods GET, POST, PUT, PATCH and DELETE.
import http from 'node:http';
const server = http.createServer((req, res) => {
// Manual URL and Method checking
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Home Page');
} else if (req.url === '/about' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Us');
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);
This is the example of create route in node.js looks complex. Now let's see how the express make it easy.
import express form 'express';
const app = express();
// Declarative route definition
app.get('/', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Us');
});
app.listen(3000);
Look the same code with express more readable, less complex.
Middleware: In express middleware play important role is execute during request-response cycle check data before the service.
It takes the three parameters ( req, res, next ). next is important in the last if it does not mention so application can be hang.
Creating first express server
Now, let's create first express server where we define a specific port and create a server.
import express from "express";
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on PORT: ${PORT}`);
});
Handling GET request
import express from "express"
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
console.log("GET Route");
})
app.listen(PORT, () => {
console.log(`Server is running on PORT: ${PORT}`);
});
Handling POST request
import express from "express"
const app = express();
const PORT = 3000;
app.post("/api", (req, res) => {
console.log("POST Route");
})
app.listen(PORT, () => {
console.log(`Server is running on PORT: ${PORT}`);
});
In this route we get data from req.body then validate and perform other task like DB calling. Here is just mention console.log
Sending responses
Now, let's see the how to send response
app.get("/", (req, res) => {
res.json({ status: 200, message: "Fresh Data"});
})