𝗗𝗮𝘆 𝟯𝟳 𝗼𝗳 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗠𝗘𝗥𝗡 𝗦𝘁𝗮𝗰𝗸
I am on day 37 of my MERN stack journey.
Yesterday I set up structural routing for pages like /about and /contact. Today I moved into backend development. I focused on URL parsing and query parameters.
When you search for a product on a website, the data lives in the URL. I learned how to read and use this data in Node.js.
A URL is more than a string of text. It is a structured object. Here is how it works:
- Pathname: This is the main location, such as /search or /api/products.
- Query: These are the data pairs after the question mark, such as ?name=ali&id=7.
I used the url module to break down these addresses. The parser turns the raw URL into a usable object.
Here is the code I used today:
const http = require("http"); const url = require("url");
const server = http.createServer((req, res) => { let parsedUrl = url.parse(req.url, true); let pathname = parsedUrl.pathname; let queryData = parsedUrl.query;
if (pathname === "/search") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Searching logs for user: ${queryData.name} with ID: ${queryData.id}`);
} else {
res.end("Standard Endpoint View");
}
}); server.listen(8000);
This method converts query text into a clean JavaScript object. It makes data handling simple and efficient.
Source: https://dev.to/ali_hamza_589ec7b3eb6688d/day-37-of-learning-mern-stack-4758