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.

  • app is 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.

0
Subscribe to my newsletter

Read articles from Sahana S Acharya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sahana S Acharya
Sahana S Acharya