How to handle middleware, routes and routers in express

Hello guys, sorry to disturb you all; I have some doubts concerning the following terminologies and how they are used in express js: middleware , routes and routers. From what I have understood, middleware is just the middleman sitting in between a request and a respond which has the abilities to modify our request and respond object. Routes are simply the endpoint of our urls, like http/localhost:3030/abc/endpoint. Routers are the things that modularize our script by handling specific routes; like routers create dedicated "rooms" to handle specific routes. I'm What I'm confused about is the use of app.use() and when creating a new instance of : router = express.Router(), what does the express.Router() does? Because in our main script, this will be used as argument in the app.use, like app.use(router). What is happening here? How is app.use behaving as a middleware.... I understand the terminologies but I'm having some difficulties to visualise how they work in real time.
4 Replies
Faker
FakerOP2mo ago
For e.g consider the following codes:
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import {router} from '../routes/root.js'


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const port = 8080;
const app = express();

// Serve static file
app.use('/M0096732', express.static(path.join(__dirname, '../public')));

// Handle form submission
app.use(express.urlencoded({extended : false}));


app.use('/M0096732', router);


app.listen(port, () => {
console.log(`Server started on port ${port}`);
})
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import {router} from '../routes/root.js'


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const port = 8080;
const app = express();

// Serve static file
app.use('/M0096732', express.static(path.join(__dirname, '../public')));

// Handle form submission
app.use(express.urlencoded({extended : false}));


app.use('/M0096732', router);


app.listen(port, () => {
console.log(`Server started on port ${port}`);
})
import express from 'express';
import path from 'path';
import {fileURLToPath} from 'url';


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const router = express.Router();

router.get('/form(.html)?', (req,res) => {
res.sendFile(path.join(__dirname, '../public/HTML/form.html')); // sending our initial web page.
});

export {router};
import express from 'express';
import path from 'path';
import {fileURLToPath} from 'url';


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const router = express.Router();

router.get('/form(.html)?', (req,res) => {
res.sendFile(path.join(__dirname, '../public/HTML/form.html')); // sending our initial web page.
});

export {router};
What's happening each time we are using the app.use() ? Or what's happening each time we create a new instance of express.Router() and use it please. Even to serve our static files, we use app.use() but I didn't really understand why, can't we use app.get() ?
glutonium
glutonium2mo ago
app.use() tells the app to use the middleware u pass for every request sent to the server if i can recall correctly and they are called in the same order u set them app.use(a) app.use(b) app.use(c) eberytime a request is sent to the server , the server will first execute these middlewares in sequence a -> b -> c router = express.Router() Router here is a class in the express module. this router, handles your routes , it lets u "modularize our script by handling specific routes" like u said. now this is a middleware of its own. nodejs doesnt know anything about your "modular" project structure. where each routes are handled and all. these all (things related to routing) are handled by the router . so before any request is is processed, the express app needs to use the router middleware to set things up . so u tell the express app, app.use(router), meaning, "hey you, yes you, you dirty lil express app. execute the router, let this him cook first before any request is processed". and so the app does. - so essentially, app.use() lets the express app know what middlewares to use - middlewares are just codes that r ran before req is handled - router is a middleware that handles routing - app.use(router) tells the app to use the router for every request sent to the server
Faker
FakerOP2mo ago
yep I see, ty !
glutonium
glutonium2mo ago
welcm
Want results from more Discord servers?
Add your server