Skip to main content

Command Palette

Search for a command to run...

L8. ⚑ Node.js + Express.js – Server & Routing

Published
β€’1 min readβ€’View as Markdown
// 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.