Skip to main content

Command Palette

Search for a command to run...

L10. ๐ŸŒ Express.js โ€“ Serving HTML & JSON

Published
โ€ข2 min readโ€ขView as Markdown
// CREATING SERVER USING EXPRESS ๐Ÿš€

import express from 'express';
import path from 'path';

const app = express(); // initialize express app

// Product array with objects ๐Ÿœ๐ŸฅŸ
const products = [
    { title: 'noodles', price: 100 },
    { title: 'momos', price: 150 },
    { title: 'manchurian', price: 200 },
];

// Send response on root route ('/') ๐Ÿ”
app.get('/', (req, res) => {
    // Sending JSON response ๐Ÿ“ฆ (Uncomment if needed)
    // res.json({
    //     message: 'fetch all products',
    //     products: products,
    //     success: true,
    // });

    // Or sending plain HTML ๐Ÿ“
    // res.send('<h1>You are requested for home page</h1>');

    // Sending HTML file ๐Ÿ“‚
    const dir = path.resolve(); // get current directory
    const url = path.join(dir, './index.html'); // build full path to HTML file
    res.sendFile(url); // send file as response
});

// Start the server on port 2000 ๐Ÿšช
const port = 2000;
app.listen(port, () => console.log(`Server is running on port ${port}`));

โœจ Explanation

  • Used Express.js instead of http module for cleaner syntax.

  • Defined a products array containing objects (like a mini-database).

  • In the route /, we:

    • Can return JSON using res.json()

    • Can send plain HTML using res.send()

    • Or send a full HTML file using res.sendFile(), using the path module to locate the file.

  • Server runs on port 2000 and handles the homepage /.