L8. β‘ Node.js + Express.js β Server & Routing
// SERVER & ROUTING IN EXPRESS.JS βοΈ
// In Node.js, we used 'http' module to create a server
// In Express.js, it's much easier and faster π
import express from 'express';
// Call express as a function to create the app instance π§
const app = express();
// ROUTING π£οΈ
// Home route '/'
app.get('/', (req, res) => {
res.send("You are requested for home route");
});
// Contact route '/contact'
app.get('/contact', (req, res) => {
res.send("You are requested for contact page");
});
// Define a port πͺ
const port = 2000;
// Start the server π₯
app.listen(port, () => console.log(`Server is running on port ${port}`));
β¨ Explanation
Express is a Node.js framework that makes it easy to build servers.
appis your Express server instance.app.get()is used to define routes like/and/contact.res.send()sends plain text (or HTML) as a response to the client.You donβt need
http.createServer()here β Express handles it internally.