𝗗𝗮𝘆 𝟰𝟰 𝗼𝗳 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗠𝗘𝗥𝗡 𝗦𝘁𝗮𝗰𝗸
My Express.js server used to send only JSON data. Today I changed that.
I learned how to serve HTML, CSS, and images directly from my backend. This moves my project from a simple API to a full-stack application.
I followed the Complete Coding backend track to master file routing.
In a real production environment, you need an efficient way to deliver frontend files. You should not write custom loops to read files.
Here is the setup I used today:
express.static() Middleware Express includes a built-in tool called express.static(). It lets you pick a folder, like public or assets, to serve to the browser.
path.join() I used the Node.js path module and the __dirname variable. This ensures my server finds files on Windows, Linux, or Mac without errors.
Here is the code:
const express = require("express"); const path = require("path"); const app = express(); const PORT = 8000;
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "public", "index.html")); });
app.listen(PORT, () => {
console.log(Server running on http://localhost:${PORT});
});
Building these basics helps me understand how the web works.
Source: https://dev.to/ali_hamza_589ec7b3eb6688d/day-44-of-learning-mern-stack-3c0m