L10. ๐ Express.js โ Serving HTML & JSON
// 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
httpmodule for cleaner syntax.Defined a
productsarray 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 thepathmodule to locate the file.
Server runs on port
2000and handles the homepage/.