𝗗𝗮𝘆 𝟯𝟲 𝗼𝗳 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗠𝗘𝗥𝗡 𝗦𝘁𝗮𝗰𝗸
I am on day 36 of my MERN stack journey.
Yesterday I built my first local web server. Today I focused on backend routing.
Routing tells your server how to handle different requests. The backend acts as a traffic controller. It decides which content to show based on the URL.
I learned how to use the req.url property. This property holds the path a user types into their browser.
You use logical conditions to send users to the right place.
Here is how the logic works:
- The server checks the incoming URL.
- If the URL is "/", the server sends the homepage.
- If the URL is "/about", the server sends the about page.
- If the URL matches nothing, the server sends a 404 error.
This process keeps your application organized and functional.
Code example:
const server = http.createServer((req, res) => { if (req.url === "/") { res.end("Welcome to the Homepage!"); } else if (req.url === "/about") { res.end("This is the About Page detailing our stack."); } else { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404: Page Not Found!"); } });
Source: https://dev.to/ali_hamza_589ec7b3eb6688d/day-36-of-learning-mern-stack-183m